MySQLdb AttributeError: 'module' object has no attribute 'commit' MySQLdb AttributeError: 'module'对象没有'commit'属性
MySQLdb AttributeError: 'module' object has no attribute 'commit' MySQLdb AttributeError: 'module'对象没有'commit'属性
我正在尝试按照这个教程连接和插入到我的机器上的MySQL数据库,但却遇到了困难。一切看起来都很顺利,直到实际提交更改的那一点。我收到了一个错误:\n
Traceback (most recent call last): File "write.py", line 18, indb.commit() AttributeError: 'module' object has no attribute 'commit'
\n我按照这些指示在我的Mac上安装了Python,并且我的代码如下:\n
#!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()
\n我在任何地方都没有找到关于这种类型错误的参考,这真的没有道理。我真的很感激任何帮助或指导。谢谢!
MySQLdb模块中没有commit属性,因此在使用MySQLdb进行数据库操作时会出现AttributeError: 'module' object has no attribute 'commit'的错误。
解决方法是,需要使用连接对象(connection object)进行commit操作,而不是使用MySQLdb模块本身。具体代码如下:
con.commit()
在这段代码中,con表示连接对象,通过调用commit()方法来提交数据库操作。这样就可以避免AttributeError: 'module' object has no attribute 'commit'的错误出现。
需要注意的是,db是MySQLdb模块的别名,而con是连接对象。在进行数据库操作时,应当使用连接对象来进行commit操作,而不是直接使用MySQLdb模块本身。
通过以上的解决方法,我们可以避免出现MySQLdb AttributeError: 'module' object has no attribute 'commit'的错误,并成功进行数据库操作。