今天寫的一個小功能,里面要用MySQLdb更新數據庫,語句如下
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'
語句沒問題,數據庫中也存在username為'test@163.com'的記錄,并且手動執行也是正確的(status被正確的更新為1)
但奇怪的就是在Python中用MySQLdb更新的時候沒有效果
原因就是suspects.account_operation這張表用的InnoDB引擎,InnoDB是事務性引擎,有個autocommit的變量控制是否自動提交事務。InnoDB默認的autocommit=1,也就是說,每條語句都是一個事務,都會被自動提交。但如果設置autocommit=0,關閉自動提交的話,就需要我們手動commit了。commit之前的所有更新都在一個事務內,如果不commit的話,這些更新都不會生效。
?
用MySQL的客戶端連接時,autocommit=1,是會自動提交的。有意思的是,MySQLdb這個庫默認autocommit=0,所以需要手動提交。
下面是MySQLdb的關于autocommit的說明,從1.2.0版本開始,默認禁用autocommit。
鏈接:http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away
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.
?
上面這些內容都是針對InnoDB的,對于MyISAM這樣的非事務性引擎,不存在事務概念,只管更新即可,autocommit是0或1都沒有影響。