【mysql】MySQLdb中的事务处理

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

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

 

例:sql

#!/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','1')"
            self.cursor.execute(sql)
            sql = "update test_distinct set type='2' 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","12345678","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()

结果:测试

能够正确查询到新插入的数据,而且数据成功回滚,没有写入数据。fetch

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

 

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

相关文章
相关标签/搜索