【mysql】MySQLdb中的事务处理

时间:2023-03-09 21:56:23
【mysql】MySQLdb中的事务处理

MySQL数据库有一个自动提交事务的概念,autocommit。含义是,如果开启autocommit, 则每一个语句执行后会自动提交。即一个语句视为一个事务。

在python使用的MySQLdb中,默认是不开启autocommit的。所以,只有在显示commit后,数据库操作才会真正提交。或者在rollback()后,回滚到上一次commit的状态。

例:

#!/bin/env python
#coding=utf-8 import MySQLdb class MYSQL(object):
def __init__(self):
self.db = MySQLdb.connect("localhost","root","12345678","TESTTABLE",charset='utf8')
self.cursor = self.db.cursor() def test(self):
try:
sql = "insert into test_distinct(name, type) values('t3','')"
self.cursor.execute(sql)
sql = "update test_distinct set type='' where name='t3'"
#raise #打开用于测试异常
self.cursor.execute(sql)
except:
self.db.rollback() #出现异常,不会提交任何数据变化
else:
self.db.commit() #正常处理,提交数据变化(如果没有这一句,也是不会提交任何变化的) if __name__ == "__main__":
obj = MYSQL()
obj.test()

场景:在两次插入语句直接有一个查询语句

#!/bin/env python
#coding=utf-8 import MySQLdb class MYSQL(object):
def __init__(self):
self.db = MySQLdb.connect("localhost","root","","TESTTABLE",charset='utf8')
self.cursor = self.db.cursor() def test(self):
try:
name = 't5'
#insert
sql = "insert into test_distinct(name, type) values('%s','1')" % name
self.cursor.execute(sql)
#search
sql = "select * from test_distinct where name = '%s'" % name #查询新插入的数据
self.cursor.execute(sql)
res = self.cursor.fetchone()
print res
#insert
sql = "update test_distinct set type='2' where name='%s'" % name
raise #引起异常
self.cursor.execute(sql)
except:
self.db.rollback()
else:
self.db.commit() if __name__ == "__main__":
obj = MYSQL()
obj.test()

结果:

可以正确查询到新插入的数据,并且数据成功回滚,没有写入数据。

结论:虽然没有commit时,数据库不会真正变化,但是会有一个临时变化的版本,供我们查询还未真正加入的数据。

注意:上面的结果是建立在mysql使用的存储引擎支持事务的基础上的。如果用MyISAM,则即使像上面一样写代码,也会默认一句话就提交一次的,因为MyISAM不支持事务。