Try-except for flow control in reading Sqlite

Victor Hooi victorhooi at gmail.com
Thu Oct 31 19:08:38 EDT 2013


Hi,

You're right, if the databse doesn't exist, the sqlite3 library will simply create it.

Hmm, in that case, what is the Pythonic way to handle this then?

If the database is new, then it won't have the table I need, and it will return something like:

    sqlite3.OperationalError: no such table: my_table

I suppose I can try the query, and catch OperationalError, and if so, create the new schema then?

However, that seems a bit ugly, as I'm guessing OperationalError could be caused by a number of other reasons?

Should I perhaps be using some kind of version table as Burak Aslan suggested?

Cheers,
victor 

On Tuesday, 29 October 2013 10:43:19 UTC+11, Dennis Lee Bieber  wrote:
> On Sun, 27 Oct 2013 20:43:07 -0700 (PDT), Victor Hooi
> 
> <victorhooi at gmail.com> declaimed the following:
> 
> 
> 
> >Hi,
> 
> >
> 
> >I'd like to double-check something regarding using try-except for controlling flow.
> 
> >
> 
> >I have a script that needs to lookup things in a SQLite database.
> 
> >
> 
> >If the SQLite database file doesn't exist, I'd like to create an empty database, and then setup the schema.
> 
> >
> 
> >Is it acceptable to use try-except in order to achieve this? E.g.:
> 
> >
> 
> >    try:
> 
> >        # Try to open up the SQLite file, and lookup the required entries
> 
> >    except OSError:
> 
> >        # Open an empty SQLite file, and create the schema
> 
> >
> 
> >
> 
> 	In my experience, SQLite will /create/ an empty database file if the
> 
> specified name does not exit. So just executing the connect() call is all
> 
> that is needed. After all, checking for data IN the database will either
> 
> return something or fail at that point in which case you can now populate
> 
> the schema.
> 
> 
> 
> -=-=-=-=-=-
> 
> >>> import sqlite3 as db
> 
> >>> con = db.connect("anUnknown.db")
> 
> >>> cur = con.cursor()
> 
> >>> rst = cur.execute("pragma table_info('aTable')")
> 
> >>> rst
> 
> <sqlite3.Cursor object at 0x0000000004725C00>
> 
> >>> for ln in rst:
> 
> ... 	print ln
> 
> ... 	
> 
> >>> for ln in cur:
> 
> ... 	print ln
> 
> ... 	
> 
> >>> rst = cur.execute("create table aTable ( junk varchar )")
> 
> >>> con.commit()
> 
> >>> rst = cur.execute("pragma table_info('aTable')")
> 
> >>> for ln in rst:
> 
> ... 	print ln
> 
> ... 
> 
> (0, u'junk', u'varchar', 0, None, 0)
> 
> >>> 
> 
> 
> 
> 
> 
> 	No try/except needed -- just an a conditional testing the length of the
> 
> result returned by the pragma instruction on the table you expect to find
> 
> in the database.
> 
> -- 
> 
> 	Wulfraed                 Dennis Lee Bieber         AF6VN
> 
>     wlfraed at ix.netcom.com    HTTP://wlfraed.home.netcom.com/



More information about the Python-list mailing list