我和老师的基本一样就是不触发异常回滚
我这儿遇到了问题,异常了不处理,第一条第二条都执行了,没回滚不知道啥情况
在Linux上做的
我这儿遇到了问题,异常了不处理,第一条第二条都执行了,没回滚不知道啥情况
在Linux上做的
2016-07-02
#connection import MySQLdb conn = MySQLdb.Connect( host = '127.0.0.1', port = 3306, user = 'root', passwd = '', db = 'innodb', charset = 'utf8' ) cursor = conn.cursor() sql_insert = 'insert into stu (name) values("ddd")' sql_update = "update stu set name='小明dddd' where id=14" sql_delete = 'delete from stu where id=1111' # try: # #cursor.execute(sql_insert) # #print cursor.rowcount # #cursor.execute(sql_update) # #print cursor.rowcount # cursor.execute(sql_delete) # print cursor.rowcount # conn.commit() # except Exception as e: # print e # conn.rollbake() try: cursor.execute(sql_insert) print(cursor.rowcount) cursor.execute(sql_update) print(cursor.rowcount) cursor.execute(sql_delete) print(cursor.rowcount) conn.commit() #以上三条操作作为整体单元事务,提交数据 except Exception as e: print(e) conn.rollback() #事务出现异常回滚数据 cursor.close() conn.close()
#代码粘贴上来,看看你的情况,我刚开始出现这问题的原因是没有空四格,现在调通了
#环境:python3.5 插件和老师不太一样:是http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python中的mysqlclient
#这一段代码:
import MySQLdb
# host服务器地址,port服务器端口号,user用户名,passwd密码,db数据库名称,charset连接编码
conn = MySQLdb.Connect(
host = '127.0.0.1',
port = 3306,
user='root',
passwd='',
db='pymysql',
charset='utf8'
)
cursor = conn.cursor()
sql_insert = "insert into user(userid,username) values(10,'name10')"
sql_update = "update user set username='name91' where userid=9"
sql_delete = "delete from user where userd<3"
#事务
try:
cursor.execute(sql_insert)
print(cursor.rowcount)
cursor.execute(sql_update)
print(cursor.rowcount)
cursor.execute(sql_delete)
print(cursor.rowcount)
conn.commit() #以上三条操作作为整体单元事务,提交数据
except Exception as e:
print(e)
conn.rollback() #事务出现异常回滚数据
cursor.close()
conn.close()
举报