在 python 中对 SQL 语句使用 execute()/executemany()

Using execute()/executemany() for SQL statements in python

我正在使用 python 中的 MySQLdb 模块编写 SQL 语句。我很难按照自己喜欢的方式使用变量。这是我的作品:

stmt = '''
INSERT INTO Table1
(name, status)
SELECT (:name1, :status1)
        FROM dual
WHERE NOT EXISTS (
        SELECT 1 FROM Table1
        WHERE name =(:name1))
'''
dic = {"name1":"Bob", "status1":"Active"}

dbcursor.executemany(stmt, dic) 
dbconnection.commit()
print("Insertion to Table1 committed\n\n")

这不起作用,我最终回滚了错误消息 not all arguments converted during string formatting。如果我在其中硬编码字典值,则插入工作正常。你能告诉我使用变量代替硬编码值的正确方法吗?

executemany() 接受参数对象(字典)的 序列 ,但您只传入 一个 。要么使用 dbcursor.execute(),要么传入一系列字典。由于您只有一本字典,因此只需使用 dbcursor.execute():

dbcursor.execute(stmt, dic)

因为 executemany() 将第二个参数视为一系列参数,每个参数都在单独的 execute() 调用中使用,因此您实际上是在尝试 运行 使用keys 的字典作为参数。实际上,将 dic 作为参数传递会产生:

for key in dic:
    dbcursor.execute(stmt, key)

其中键也是可迭代的,生成单独的 个字符 作为使用的参数。您正在尝试 运行 带有 ('n', 'a', 'm', 'e', '1')('s', 't', 'a', 't', 'u', 's', '1') 的语句。这对您的陈述不起作用。