python mysql 插入数据事务提交与异常处理代码
import mysql.connector try: config = { "host": "localhost", "port": 3306, "user": "root", "password": "root", "database": "yu1" } con = mysql.connector.connect(**config) # 开启事务 con.start_transaction() # 创建游标 cursor = con.cursor() sql = "INSERT INTO student(stuid,name,sex,age,email) VALUES ('202210','阿发','男',19,'6898765@qq.com')" cursor.execute(sql) # 事务提交 con.commit() except Exception as e: # 出现问题,事务回滚 if "con" in dir(): con.rollback() print(e) finally: if "con" in dir(): con.close()