要在事务中执行SQL语句,可以按照以下步骤进行操作:
connection = pymysql.connect(host='localhost', user='root', password='password', database='mydatabase')
cursor = connection.cursor()
connection.begin()
sql = "INSERT INTO table_name (column1, column2) VALUES (%s, %s)"
data = ("value1", "value2")
cursor.execute(sql, data)
connection.commit()
connection.rollback()
cursor.close()
connection.close()
通过以上步骤,就可以在一个事务中执行多个SQL语句,并确保它们要么全部成功执行,要么全部不执行。