可能有几种原因会导致begin_transaction和commit不起作用。首先,确保您正在使用支持事务的数据库引擎,如InnoDB。其次,避免在嵌套事务中使用commit。最后,请检查您的代码是否正确处理错误情况,并且正确地使用了begin_transaction和commit。例如,以下示例代码演示了如何使用事务来确保在插入新行时发生错误时回滚更改:
import mysql.connector
# Connect to the database
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# Get a cursor object
cursor = db.cursor()
try:
# Begin transaction
db.begin()
# Insert a new row into the table
sql = "INSERT INTO mytable (name, age) VALUES (%s, %s)"
values = ("John", 30)
cursor.execute(sql, values)
# Raise an error to simulate a problem
raise Exception("Something went wrong")
# Commit the transaction
db.commit()
except Exception as e:
# Rollback the transaction
db.rollback()
print("Transaction rolled back")
finally:
# Close the connection
db.close()
以上代码将尝试将新行插入名为“mytable”的表中。然后,它会抛出一个错误以模拟问题。如果事务失败,则会回滚更改。如果一切正常,则会提交更改。