MySQLdb AttributeError:' module'对象没有属性' commit'

时间:2015-02-21 07:08:12

标签: python mysql mysql-python

我正在尝试连接并在this tutorial之后插入到我的机器上的MySQL数据库中,我感到难过。在实际提交更改之前,一切似乎都很好看。我收到一个错误:

Traceback (most recent call last):
  File "write.py", line 18, in <module>
    db.commit()
AttributeError: 'module' object has no attribute 'commit'

我已按照these instructions在我的Mac上安装Python,我的代码如下:

#!usr/bin/python

import MySQLdb as db

try:
    con = db.connect(host='localhost', user='trevor', passwd='pw', db='aqi');

    cur = con.cursor()

    sql_statement = """INSERT INTO aqi(datetime, no2, o3, so2, co, pm10, pm25, aqi, health_range)
                       VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"""
    print sql_statement

    cur.execute(sql_statement, ("some date", 13.2, 53.5, 45.4, 31.1, 31.1, 32.3, 33.4, "healthy"))

    db.commit()

except db.Error, e:

    print "Error %d: %s" % (e.args[0],e.args[1])
    sys.exit(1)

finally:

  if con:
    con.close()

我在任何地方都找不到任何关于此类错误的引用,但它确实没有意义。我真的很感激任何帮助或方向。谢谢!

1 个答案:

答案 0 :(得分:1)

您需要进行连接提交而不是db:

con.commit()

db是模块MySQLdb的别名,con是连接对象。