【问题标题】:MySQLdb AttributeError: 'module' object has no attribute 'commit'MySQLdb AttributeError:“模块”对象没有属性“提交”
【发布时间】:2015-04-22 23:18:07
【问题描述】:

我正在尝试按照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()

我在任何地方都没有找到对此类错误的任何引用,这确实没有意义。我真的很感激任何帮助或指导。谢谢!

【问题讨论】:

  • 注意datetime 是保留工作不要将其用作列名,否则使用`
  • 谢谢@GrijeshChauhan。我很欣赏这张纸条。我对 SQL 还是很陌生。

标签: python mysql mysql-python


【解决方案1】:

你需要做连接提交而不是数据库:

con.commit()

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

【讨论】:

    猜你喜欢
    • 2010-11-18
    • 2018-08-28
    相关资源
    最近更新 更多