Do or do not…the use of Try, with Python and sqlite

 2009.21.10 -  Jeffrey Forman

I’ve been hacking around writing random Django apps and scripts lately and came across something I had been meaning to look into over the past couple weeks. What happens when you select a row of data from a database (mysql, sqlite, whatever), that comes back empty and you try to iterate over it? Example: select * from authinfo where username = “foo”, and the user ‘foo’ does not exist.

At first I thought:

if db_query.fetchone()[0]:

would work, but this only gives an error “TypeError: ‘NoneType’ object is unsubscriptable.”

Then I remembered the try/except syntax, which worked great in this instance.

#!/usr/bin/env python import sqlite3 username \= “testuser1” password \= “foobar” conn \= sqlite3.connect(“/home/jforman/testsqlite.db”) c \= conn.cursor() db_query \= c.execute(“select username from authinfo where username = ‘%s’” % username) try: db_output \= db_query.fetchone()[0].strip() print “output: %s” % db_output except TypeError: print “no user found” c.close() conn.close()

Am I expecting too much that Python can handle iterating over an empty line (and just skip the whole thing) ? Or is this just how it’s done, where every database query-related line is done in a try stanza?