当前位置:Gxlcms > 数据库问题 > 【mysql】MySQLdb中的事务处理

【mysql】MySQLdb中的事务处理

时间:2021-07-01 10:21:17 帮助过:38人阅读

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()

结果:

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

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

【mysql】MySQLdb中的事务处理

标签:语句   变化   port   etc   insert   事务   imp   l数据库   python   

人气教程排行