# 引入模块
import pymysql
# 创建连接对象
cnn = pymysql.connect(
host='localhost',
port=3306, # 注意: 端口后一定是整型
user='root',
password='123456',
database='my_test',
charset='utf8' # 注意:此处是utf8, 不是utf-8
)
# 创建游标对象
cur = cnn.cursor(cursor=pymysql.cursors.DictCursor)
# 准备sql语句 -- 曹操的钱增加50
sql1 = "update student set money = money + 50 where stu_name = '曹操'"
# 准备sql语句 -- 袁绍的钱减少50
sql2 = "update student set money = money - 50 where stu_name = '袁绍'"
# 执行sql语句
result1 = cur.execute(sql1) # 这个地方是否可以判断sql1执行成功了吗? 如果是0表示没有成功, 如果是非0表示成功
result2 = cur.execute(sql2) # 这个地方是否可以判断sql2执行成功了吗? 如果是0表示没有成功, 如果是非0表示成功
print(result1, result2)
# 根据执行sql语句的返回值是都为非0,还是有0存在进行判断
if result1 != 0 and result2 != 0:
# 提交事务
print("提交了事务")
cnn.commit()
else:
# 回滚事务
print("回滚了事务")
cnn.rollback()
# 关闭
cur.close()
cnn.close()
事务的操作
最新推荐文章于 2022-09-04 17:06:43 发布