问题描述
我在更新 MySQL 数据库中的一行时遇到了一些问题.这是我尝试运行的代码:
I'm having some trouble updating a row in a MySQL database. Here is the code I'm trying to run:
import MySQLdb
conn=MySQLdb.connect(host="localhost", user="root", passwd="pass", db="dbname")
cursor=conn.cursor()
cursor.execute("UPDATE compinfo SET Co_num=4 WHERE ID=100")
cursor.execute("SELECT Co_num FROM compinfo WHERE ID=100")
results = cursor.fetchall()
for row in results:
print row[0]
print "Number of rows updated: %d" % cursor.rowcount
cursor.close()
conn.close()
我运行这个程序时得到的输出是:
The output I get when I run this program is:
4
更新的行数:1
4
Number of rows updated: 1
它似乎正在运行,但如果我从 MySQL 命令行界面 (CLI) 查询数据库,我发现它根本没有更新.但是,如果我从 CLI 输入 UPDATE compinfo SET Co_num=4 WHERE ID=100;
数据库会按预期更新.
It seems like it's working but if I query the database from the MySQL command line interface (CLI) I find that it was not updated at all. However, if from the CLI I enter UPDATE compinfo SET Co_num=4 WHERE ID=100;
the database is updated as expected.
我的问题是什么?我在 Windows 机器上运行 Python 2.5.2 和 MySQL 5.1.30.
What is my problem? I'm running Python 2.5.2 with MySQL 5.1.30 on a Windows box.
推荐答案
我不确定,但我猜你正在使用 INNODB 表,而且你还没有完成提交.我相信 MySQLdb 会自动启用事务.
I am not certain, but I am going to guess you are using a INNODB table, and you haven't done a commit. I believe MySQLdb enable transactions automatically.
在调用 close
之前调用 conn.commit()
.
Call conn.commit()
before calling close
.
来自常见问题解答:从 1.2.0 开始,MySQLdb 默认禁用自动提交
这篇关于数据库不会使用 MySQL 和 Python 自动更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!