Do or do not…the use of Try, with Python and sqlite
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?
Michael Marineau 8:57 pm on October 21, 2009 Permalink |
It’s a little cleaner to use an if rather than a try/except:
db_query = c.execute(“blah”)
row = db_query.fetchone()
if row:
print “row 1: %s” % row[0]
else:
print “nothing found”
Steve Laniel 7:49 am on October 22, 2009 Permalink |
Right; I second Mike. Jeff, the thing to remember is that an empty list evaluates to False. That’s why “if row: foo” works.
In C and C++ and Perl, you could compress those rather nicely:
if( row = db_query.fetchone() ) {
doSomethingWith(row);
}
else {
doSomethingElse();
}
One happy consequence of putting the row inside the if() is that the row goes out of scope when you leave the if/else. Whereas in Python, that row is sticking around even when you’re done with it.
Jeff Forman 7:54 am on October 22, 2009 Permalink |
@Mike and @Steve,
I could have swore I tried doing what you guys suggested and throwing it in an if/else block, but I got that type error. Yay computer languages. Good to know for next time.