在MySQL(版本5.6.32-78.1)中 我有2个名为 Test1 的表, Test2 (比如说), 其中 Test1 有一个触发器( INSERT后) 第三个名为 Test1A 的表。
我在 python 3.6 中使用 MySQLdb 模块来处理我的数据库。
我正在尝试将 Test1 和 Test2 中的2个单独插入捆绑到一个事务中。我遇到的问题是,由于第二个插入中的错误导致整个事务可能被回滚,而在 Test1 中的插入之后触发的触发结果是< strong> NOT 正在回滚。
因此,在回滚之后,我们会在事务之前返回到表 Test1 和 Test2 的状态,但是,触发器对 Test1 <的影响< / strong>遗骸。
任何想法/建议?
这是型号代码
import MySQLdb
cnn = MySQLdb.connect (host = "hostname", user = "username",
passwd = password", db = "dbname")
cursor = cnn.cursor()
try:
cursor.execute( "SET AUTOCOMMIT = 0 " )
print('done with step 1')
s = "Insert INTO Test1 ( field1) Values (%s ) "
cursor.execute(s, ( 'abc', ) ) # this fires a trigger
print('done with step 2')
s = "Insert INTO Test2 (ID, field1) Values (%s, %s)"
cursor.execute( s , ('1', 'aa' ) )
print('done step 3')
cursor.close()
cnn.commit()
print('DONE')
except:
cnn.rollback() # the effect of the trigger on Test1 is not being
print('Rollbacked') # rolled back
Test1上的触发器是
INSERT INTO
Test1A (field1)
SELECT
Test1.field1 FROM Test1
WHERE
Test1.ID = NEW.ID
一些评论:
如果我没有关闭自动提交,则会在每个上面调用commit 在上面插入声明,这似乎是必要的。
当然,有人可能建议将 Test1 作为最后一个表格 交易,但这不是一个选项,因为我可能需要来自 Test1 的信息(比如说新ID)来操作 Test2 。
答案 0 :(得分:0)
今天已经发布了这个,但无论如何你去了:
import pymysql
id = input("Id : ")
name = input("Name : ")
cursor = con.cursor()
cursor.execute(""" INSERT INTO names (id, name) VALUES("%s", "%s")"""
%(id, name))
con.commit()
con.close()
您可以在此问题上看到我的回复: MySQL db call: not all arguments converted during string formatting Ask