事务与上下文

多步写库要绑成事务,要么全成功要么全回滚。PyMySQL 默认就是事务模式,出错 rollback 即可;另外用 with 上下文能自动关连接,省去手写 close。

事务与上下文要点

事务与上下文示例

						# 手动事务
						try:
						    cursor.execute("START TRANSACTION")
						    cursor.execute("UPDATE account SET balance = balance - 100 WHERE id = 1")
						    cursor.execute("UPDATE account SET balance = balance + 100 WHERE id = 2")
						    db.commit()
						except Exception as e:
						    db.rollback()
						    print("回滚:", e)

						# with 自动关连接
						import pymysql
						from contextlib import closing
						with closing(pymysql.connect(host="127.0.0.1", user="app_user", password="app_pass", database="shop_db")) as db:
						    with closing(db.cursor()) as cur:
						        cur.execute("SELECT * FROM product")
						        for row in cur.fetchall():
						            print(row)
避坑提醒:with 只负责关闭连接,不负责提交;里面写了写操作却没 commit,退出时改动直接丢,别忘了提交。
事务与上下文 · Python 连接 知识卡片
卡片 05 / 06 · Python 连接(1080×1440 速查卡片)

Python 连接知识点