python mysql autocommit_MySQLdb autocommit的坑
今天寫的一個(gè)小功能,里面要用MySQLdb更新數(shù)據(jù)庫,語句如下
sql = "update %s.account_operation set status=1 where username='%s'" % (allResDBInfos['db'], username)
變量替換后,是下面的樣子
update suspects.account_operation set status=1 where username='test@163.com'
語句沒問題,數(shù)據(jù)庫中也存在username為'test@163.com'的記錄,并且手動(dòng)執(zhí)行也是正確的(status被正確的更新為1)
但奇怪的就是在Python中用MySQLdb更新的時(shí)候沒有效果
原因就是suspects.account_operation這張表用的InnoDB引擎,InnoDB是事務(wù)性引擎,有個(gè)autocommit的變量控制是否自動(dòng)提交事務(wù)。InnoDB默認(rèn)的autocommit=1,也就是說,每條語句都是一個(gè)事務(wù),都會(huì)被自動(dòng)提交。但如果設(shè)置autocommit=0,關(guān)閉自動(dòng)提交的話,就需要我們手動(dòng)commit了。commit之前的所有更新都在一個(gè)事務(wù)內(nèi),如果不commit的話,這些更新都不會(huì)生效。
用MySQL的客戶端連接時(shí),autocommit=1,是會(huì)自動(dòng)提交的。有意思的是,MySQLdb這個(gè)庫默認(rèn)autocommit=0,所以需要手動(dòng)提交。
下面是MySQLdb的關(guān)于autocommit的說明,從1.2.0版本開始,默認(rèn)禁用autocommit。
My data disappeared! (or won't go away!)
Starting with 1.2.0, MySQLdb disables autocommit by default, as required by the DB-API standard (PEP-249). If you are using InnoDB tables or some other type of transactional table type, you'll need to do connection.commit() before closing the connection, or else none of your changes will be written to the database.
Conversely, you can also use connection.rollback() to throw away any changes you've made since the last commit.
Important note: Some SQL statements -- specifically DDL statements like CREATE TABLE -- are non-transactional, so they can't be rolled back, and they cause pending transactions to commit.
上面這些內(nèi)容都是針對(duì)InnoDB的,對(duì)于MyISAM這樣的非事務(wù)性引擎,不存在事務(wù)概念,只管更新即可,autocommit是0或1都沒有影響。
總結(jié)
以上是生活随笔為你收集整理的python mysql autocommit_MySQLdb autocommit的坑的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 编写有效用例电子版_软件测试人员必须编写
- 下一篇: mysql加锁后怎么解除_Mysql查看