# 导包import pymysql# 捕获异常conn,cursor = None, None # 提前定义变量,防止出现异常之后,没有变量的问题try :# 建立连接conn = pymysql.connect(host=\"localhost\", user=\"root\", password=\"root\",database=\"books\", port=3306, charset=\"utf8\")# 获取游标cursor = conn.cursor()# 先执行插入三体这本书的操作cursor.execute(\"insert into t_book(`id`,`title`,`pub_date`) values(11, \'三体\', \'1970-01-01\');\")# 再执行插入逻辑人物的操作cursor.execute(\"insert into t_hero(id, `name`,`gender`,`book_id`) values(\'逻辑11111\', 1, 4);\")# 提交事务conn.commit()print(\"提交事务成功\")except Exception as e:# 回滚事务cursor.execute(\"select * from t_book;\")print(\"回滚之前书中有哪些数据:\",cursor.fetchall())cursor.execute(\"select * from t_hero;\")print(\"回滚之前英雄人物中有哪些数据:\", cursor.fetchall())conn.rollback() # 回滚cursor.execute(\"select * from t_book;\")print(\"回滚之后书中有哪些数据:\",cursor.fetchall())cursor.execute(\"select * from t_hero;\")print(\"回滚只会英雄人物中有哪些数据:\", cursor.fetchall())print(\"回滚事务成功\")finally:# 关闭游标和关闭连接cursor.close()conn.close()
pymysql transaction
未经允许不得转载:爱站程序员基地 » pymysql transaction