Reputation: 354
To prevent connections from being left open on the server - here's what I'm currently doing to close mysqldb's cursor and connection, then I 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"
Is there a better way to do this?
Note: I know the WITH keyword might be better, but I haven't found any documentation saying mysqldb supports the WITH keyword to close the connection automatically.
Upvotes: 1
Views: 58
Reputation: 19648
Check out this tutorial
Cited:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb as mdb
con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS Writers")
cur.execute("CREATE TABLE Writers(Id INT PRIMARY KEY AUTO_INCREMENT, \
Name VARCHAR(25))")
cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")
...
Upvotes: 1