更好 的连接 python调用事务数据库连接
import pymysql
#添加数据
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='yyy')
cursor = conn.cursor()
try:
insertSQL0="INSERT INTO ACCOUNT2 (name,balance) VALUES ('oldboy',4000)"
insertSQL1="UPDATE account2 set balance=balance-30 WHERE name='yuan'"
insertSQL2="UPDATE account2 set balance=balance+30 WHERE name='xialv'"
cursor = conn.cursor()
cursor.execute(insertSQL0)
conn.commit()//语句执行
cursor.execute(insertSQL1) 1 执行 但没有提交事务
raise Exception 2 捕捉异常
cursor.execute(insertSQL2) 6 执行语句sql 2 不执行1 ,继续异常处理只是没写了那么多insert语句
cursor.close() 7 关闭游标
conn.commit()
except Exception as e: 3 当有异常时
conn.rollback() 4 执行回滚到sql0语句执行完,不回滚那么语句sql1执行了会起作用,所以必须回滚
conn.commit() 5 结束
cursor.close()
conn.close()