Sunday, October 6, 2013

Error Handling In mysqldb - Python

I've had issues with queries failing and leaving connections open (enough to stall a server...). I know python's oursql library supports using the WITH keyword, and I think it will close the connection when there is an unexpected error. However, I'm not sure if I'm ready to move to a different library for MySQL (it's working well).

Here's what I'm currently doing to close the cursor and connection, then re-raise the error:

import MySQLdb

conn = MySQLdb.connect(user="username", passwd="secret", db="database", charset='utf8')
cur = conn.cursor()

try:
cur.execute("INSERT INTO testTable (userid) VALUES(%s);" % id)
conn.commit()
except:
cur.close()
conn.close()
raise
finally:
print "Insert Successful"

No comments:

Post a Comment