bin/env python
#coding=utf-8import 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
importMySQLdbclassMYSQL(object):def __init__(self):
self.db= MySQLdb.connect("localhost","root","12345678","TESTTABLE",charset=‘utf8‘)
self.cursor=self.db.cursor()deftest(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()printres#insert
sql = "update test_distinct set type=‘2‘ where name=‘%s‘" %nameraise#引起异常
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
本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉
本文系统来源:http://www.cnblogs.com/dplearning/p/6388059.html