捕获MySQLdb库中的错误

时间:2013-10-06 23:04:43

标签: python mysql

为了防止连接在服务器上保持打开 - 这是我正在做的关闭mysqldb的游标和连接,然后我重新提出错误:

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"

有更好的方法吗?

注意:我知道WITH关键字可能更好,但我没有找到任何文档说mysqldb支持WITH关键字来自动关闭连接。

1 个答案:

答案 0 :(得分:1)

查看此tutorial

引:

#!/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')")
    ...