#准备数据
create table account(
id int primary key auto_increment,
name varchar(20),
money double
);
insert into account values
(1,'owen',10000),
(2,'egon',1000),
(3,'jerry',1000),
(4,'kevin',1000);
# egon向owen借1000块钱
# 未使用事务
update account set money = money - 1000 where id = 1;
update account set moneys = money + 1000 where id = 2; # money打错了导致执行失败
# 在python中使用事务处理
from pymysql.err import InternalError
sql = 'update account set money = money - 1000 where id = 1;'
sql2 = 'update account set moneys = money + 1000 where id = 2;' # money打错了导致执行失败
try:
cursor.execute(sql)
cursor.execute(sql2)
conn.commit()
except InternalError:
print("转账失败")
conn.rollback()