[英]python mysql ValueError: Could not process parameters
I have some python code that adds a column to a table and then iterates through a list and adds each value to the column.我有一些 python 代码将列添加到表中,然后遍历列表并将每个值添加到列中。 It adds the column, but it does not add any of the values.
它添加列,但不添加任何值。 It gives me the error ValueError: Could not process parameters, but when I type the same commands into the mysql console then it works just fine.
它给了我错误 ValueError:无法处理参数,但是当我在 mysql 控制台中键入相同的命令时,它就可以正常工作了。 Below is the relevant portion of my code and the error message.
以下是我的代码的相关部分和错误消息。 Let me know if there is anything obviously wrong.
让我知道是否有任何明显错误。 please and thankyou.
谢谢,麻烦您了。
mycursor = mydb.cursor()
colname=input()
que="ALTER TABLE timestamps ADD {} TIMESTAMP(6) ".format(colname)
mycursor.execute(que)
print(que)
for i in range(len(res)):
val = res[i]
print(val)
sql = "INSERT INTO timestamps ({}) VALUES ('{}') ".format(colname,val)
print(sql)
mycursor.execute(sql, val)
mydb.commit()
asdf
ALTER TABLE timestamps ADD asdf TIMESTAMP(6)
2021-05-23 02:32:20.660
INSERT INTO timestamps (asdf) VALUES ('2021-05-23 02:32:20.660')
Traceback (most recent call last):
File "upload_onsets.py", line 89, in <module>
mycursor.execute(sql, val)
File "/home/ubuntu2004/.local/lib/python3.8/site-packages/mysql/connector/cursor_cext.py", line 257, in execute
prepared = self._cnx.prepare_for_mysql(params)
File "/home/ubuntu2004/.local/lib/python3.8/site-packages/mysql/connector/connection_cext.py", line 651, in prepare_for_mysql
raise ValueError("Could not process parameters")
ValueError: Could not process parameters
Since you're providing the value in the cursor.execute()
, you need to put a placeholder into the SQL, not format the value into it.由于您在
cursor.execute()
中提供值,因此您需要将占位符放入 SQL 中,而不是将值格式化为其中。
And the second argument to cursor.execute()
should be a tuple, not a single value. cursor.execute()
的第二个参数应该是一个元组,而不是单个值。
There's no need to assign sql
inside the loop, since it doesn't change.无需在循环内分配
sql
,因为它不会改变。
sql = "INSERT INTO timestamps ({}) VALUES (%s) ".format(colname)
print(sql)
for i in range(len(res)):
val = res[i]
print(val)
mycursor.execute(sql, (val,))
However, you can do this more efficiently using executemany()
instead of a loop.但是,您可以使用
executemany()
而不是循环更有效地执行此操作。
sql = "INSERT INTO timestamps ({}) VALUES (%s) ".format(colname)
vals = [(val,) for val in res]
mycursor.executemany(sql, vals)
This will combine all the inserts into a single query with multiple VALUES
lists.这会将所有插入合并到一个带有多个
VALUES
列表的查询中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.