Re: Opening a DB Connection

Gerhard Häring <[email protected]>
Newsgroups gmane.comp.python.db.pysqlite.user
Message-ID <[email protected]>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Rich Shepard wrote:
>    In both the web site documentation and Mike Owens' excellent book (except
> for the index), the examples of opening a database connect are:
> 
>    con = sqlite3.connect("name.db")
> 
> and there is no check for an error condition. As a long time C coder, and
> a newcomer to python, I feel uncomfortable assuming that the connection will
> be made without error when the application runs.
> 
>    Is my worry misplaced? If not, what is the desired way of wrapping the
> statement in a test for successful completion?

try:
    con = sqlite3.connect("name.db")
except sqlite3.Error:
    pass # handle case where database file could not be opened

Note that if the database file does not exist, SQLite tries to create an
empty database instead. You would then typically try to detect this case
and create the database schema (quick sketch):

cur = con.cursor()
cur.execute("select count(*) from sqlite_master")
numtables = cur.fetchone()[0]
if numtables == 0:
    create_schema(con)

...

def create_schema(con):
    cur = con.cursor()
    cur.execute("create ...")

If the database file could not be opened, it can have multiple reasons:

- - it is not a SQLite file
- - you lack file permissions
- - the path is wrong and the directory does not exist or you have no
permissions

- -- Gerhard
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFFHZ8rdIO4ozGCH14RAtPDAJ4jqvlLRvwu8udE1sD9WBipgVcMCQCeKtKQ
YBxkZHK84cWkzVyG1kgNGF4=
=bM47
-----END PGP SIGNATURE-----
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.