python - Catching Errors in MySQLdb Library -


to prevent connections being left open on server - here's i'm doing close mysqldb's cursor , connection, re-raise error:

import mysqldb  conn = mysqldb.connect(user="username", passwd="secret", db="database", charset='utf8') cur = conn.cursor()  try:     cur.execute("insert testtable (userid) values(%s);" % id)     conn.commit() except:     cur.close()     conn.close()     raise finally:     print "insert successful" 

is there better way this?

note: know keyword might better, haven't found documentation saying mysqldb supports keyword close connection automatically.

check out tutorial

cited:

#!/usr/bin/python # -*- coding: utf-8 -*-  import mysqldb mdb  con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');  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 writers(name) values('jack london')")     cur.execute("insert writers(name) values('honore de balzac')")     cur.execute("insert writers(name) values('lion feuchtwanger')")     cur.execute("insert writers(name) values('emile zola')")     cur.execute("insert writers(name) values('truman capote')")     ... 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -