日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

python mysql autocommit_MySQLdb autocommit的坑

發布時間:2025/3/12 数据库 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python mysql autocommit_MySQLdb autocommit的坑 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

今天寫的一個小功能,里面要用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。

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都沒有影響。

總結

以上是生活随笔為你收集整理的python mysql autocommit_MySQLdb autocommit的坑的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。