Python mySQL 更新,工作但不更新表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15271907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python mySQL Update, Working but not updating table
提问by user2144306
I have a python script which needs to update a mysql database, I have so far:
我有一个需要更新 mysql 数据库的 python 脚本,到目前为止:
dbb = MySQLdb.connect(host="localhost",
user="user",
passwd="pass",
db="database")
try:
curb = dbb.cursor()
curb.execute ("UPDATE RadioGroups SET CurrentState=1 WHERE RadioID=11")
print "Row(s) were updated :" + str(curb.rowcount)
curb.close()
except MySQLdb.Error, e:
print "query failed<br/>"
print e
The script prints Row(s) were updated :with the correct number of rows which have a RadioIDof 11. If I change the RadioIDto another number not present in the table it will say Row(s) were updated :0. However the database doesn't actually update. The CurrentStatefield just stays the same. If I copy and past the SQL statement in to PHPMyAdmin it works fine.
该脚本Row(s) were updated :使用正确的行数打印,其中 aRadioID为 11。如果我将 更改RadioID为表中不存在的另一个数字,它将显示Row(s) were updated :0. 但是数据库实际上并没有更新。该CurrentState领域只是保持不变。如果我将 SQL 语句复制并粘贴到 PHPMyAdmin 中,它就可以正常工作。
采纳答案by Lazykiddy
use
用
dbb.commit()
after
后
curb.execute ("UPDATE RadioGroups SET CurrentState=1 WHERE RadioID=11")
curb.execute ("UPDATE RadioGroups SET CurrentState=1 WHERE RadioID=11")
to commit all the changes that you 'loaded' into the mysql server
提交您“加载”到 mysql 服务器的所有更改
回答by Cyclone
As the @Lazykiddy pointed out, you have to commit your changes after you load them into the mysql.
正如@Lazykiddy 指出的那样,您必须在将更改加载到 mysql 后提交更改。
You could also use this approach to enable the auto commit setting, just after the MySQL connection initialization:
您也可以使用这种方法来启用自动提交设置,就在 MySQL 连接初始化之后:
dbb.autocommit(True)
Then, it will automatically commit the changes you made during your code execution.
然后,它会自动提交您在代码执行期间所做的更改。
回答by Lex Bryan
the two answers are correct. However, you can also do this:
两个答案都是正确的。但是,您也可以这样做:
dbb = MySQLdb.connect(host="localhost",
user="user",
passwd="pass",
db="database",
autocommit=True)
add autocommit=True
添加自动提交=真

