Thursday, June 11, 2009

python sqlite trick / tidbit

I found myself doing this a lot in Python when using sqlite3:



conn = sqlite3.connect( 'somedb' )
cursor = conn.cursor()
cursor.execute( 'SELECT * from sometable' )
for row in cursor:
do something with row


I found it easier and much more fun to use list comprehensions:



conn = sqlite3.connect( 'somedb' )
for row in [x for x in \
conn..execute( 'SELECT * from sometable' )]
do something with row


We even dispense with the cursor altogether. After discovering this, I found SQL to be a lot less painful.








No comments: