Python dict进入MySQL executemany

时间:2018-12-03 07:47:46

标签: python mysql dictionary tuples

我的语句应与语法匹配,但出现错误 Task

"Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement

怎么了?我已经定义了stmt = "UPDATE abbcards SET carPlate = '%(values)s' WHERE carId =%(id)s" params = [tuple(cusSurname.values()), tuple(cusSurname.keys())] cur.executemany(stmt, params) operation变量。

1 个答案:

答案 0 :(得分:1)

@ThePjot在他们的评论中有些正确。您正在查询字符串(%(values)s%(id)s)中使用命名占位符,因此必须以dict形式传递参数。

,您也调用executemany,它需要一个参数的列表或元组。很多时候,executemany除了在遍历execute并在每次迭代中传递参数元素的过程中多次调用params之外,什么也不做。 这意味着params的每个元素必须包含查询的完整参数集。

查看查询字符串,您需要替换两个参数。

stmt = "UPDATE abbcards SET carPlate = '%(values)s' WHERE carId =%(id)s"
# Side note: the quote chars around %(values)s are quite certainly wrong here

从您的代码示例中,您可以假设cusSurname是一则字典。 假设它看起来像这样:

cusSurname = {'1': 'a1b1c1',
              '2': 'a2b2c2',
              '3': 'a3b3c3'}

您在上面的代码中所做的就是将所有键和cusSurname的所有值传递给executemany

params = [('a1b1c1', 'a2b2c2', 'a3b3c3'), ('1', '2', '3')]

这将导致最终查询字符串为:

UPDATE abbcards SET carPlate = '\'a1b1c1\'' WHERE carId ='a2b2c2'

...,其中第一个参数元组中的一个元素未被替换,这导致mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement,然后第二条语句可以由字符串和参数组成,如下所示:

UPDATE abbcards SET carPlate = '\'1\'' WHERE carId ='2'

...并引发相同的异常。 您要做的是最终得到由您的cusSurname的各个项目组成的字典列表/元组:

stmt = "UPDATE abbcards SET carPlate = %(values)s WHERE carId =%(id)s"
params = [dict({'id': k, 'values': v}) for k,v in cusSurname.items()]
# [{'id': '1', 'values': 'a1b1c1'}, {'id': '2', 'values': 'a2b2c2'}, {'id': '3', 'values': 'a3b3c3'}]
cur.executemany(stmt, params)

或切换到位置参数:

stmt = "UPDATE abbcards SET carPlate = %s WHERE carId =%s"
params = [tuple(i) for i in cusSurname.items()]
# [('1', 'a1b1c1'), ('2', 'a2b2c2'), ('3', 'a3b3c3')]
cur.executemany(stmt, params)