I'm trying to figure out how to use the MySQLdb library in Python (I am novice at best for both of them).
我正在试图弄清楚如何在Python中使用MySQLdb库(我最好是两个人都是新手)。
I'm following the code here, specifically:
我在这里遵循代码,具体来说:
cursor = conn.cursor ()
cursor.execute ("DROP TABLE IF EXISTS animal")
cursor.execute ("""
CREATE TABLE animal
(
name CHAR(40),
category CHAR(40)
)
""")
cursor.execute ("""
INSERT INTO animal (name, category)
VALUES
('snake', 'reptile'),
('frog', 'amphibian'),
('tuna', 'fish'),
('racoon', 'mammal')
""")
print "Number of rows inserted: %d" % cursor.rowcount
cursor.close ()
conn.close ()
I can change this code to create or drop tables, but I can't get it to actually commit the INSERT
. It returns the row.count
value as expected (even when I change the value in the table, it changes to what I expect it to be).
我可以更改此代码来创建或删除表,但我无法让它实际提交INSERT。它按预期返回row.count值(即使我更改表中的值,它也会更改为我期望的值)。
Every time I look into the database with PHPMyAdmin there are no inserts made. How do I commit the INSERT
to the database?
每次我使用PHPMyAdmin查看数据库时都没有插入。如何将INSERT提交到数据库?
1 个解决方案
#1
16
You forget commit
data changes, autocommit is disabled by default:
您忘记提交数据更改,默认情况下禁用自动提交:
cursor.close ()
conn.commit ()
conn.close ()
Quoting Writing MySQL Scripts with Python DB-API documentation:
引用Python DB-API文档编写MySQL脚本:
"The connection object commit() method commits any outstanding changes in the current transaction to make them permanent in the database. In DB-API, connections begin with autocommit mode disabled, so you must call commit() before disconnecting or changes may be lost."
“连接对象commit()方法提交当前事务中的任何未完成的更改,使它们在数据库中永久保留。在DB-API中,连接以禁用自动提交模式开始,因此必须在断开连接之前调用commit(),否则更改可能会丢失“。
#1
16
You forget commit
data changes, autocommit is disabled by default:
您忘记提交数据更改,默认情况下禁用自动提交:
cursor.close ()
conn.commit ()
conn.close ()
Quoting Writing MySQL Scripts with Python DB-API documentation:
引用Python DB-API文档编写MySQL脚本:
"The connection object commit() method commits any outstanding changes in the current transaction to make them permanent in the database. In DB-API, connections begin with autocommit mode disabled, so you must call commit() before disconnecting or changes may be lost."
“连接对象commit()方法提交当前事务中的任何未完成的更改,使它们在数据库中永久保留。在DB-API中,连接以禁用自动提交模式开始,因此必须在断开连接之前调用commit(),否则更改可能会丢失“。