【问题标题】:MySQL Connector could not process parametersMySQL 连接器无法处理参数
【发布时间】:2019-06-28 08:18:10
【问题描述】:

我正在尝试遍历一个数组并将每个元素插入一个表中。据我所知,我的语法是正确的,我直接从Microsoft Azure's documentation 获取了这段代码。

try:
   conn = mysql.connector.connect(**config)
   print("Connection established")
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with the user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  cursor = conn.cursor()
data = ['1','2','3','4','5']


for x in data:
   cursor.execute("INSERT INTO test (serial) VALUES (%s)",(x))
   print("Inserted",cursor.rowcount,"row(s) of data.")

conn.commit()
cursor.close()
conn.close()
print("Done.")

当我运行时,它会到达cursor.execute(...),然后失败。这是堆栈跟踪。

Traceback(最近一次调用最后一次): 文件“test.py”,第 29 行,在 cursor.execute("INSERT INTO test (serial) VALUES (%s)",("test")) 执行中的文件“C:\Users\AlexJ\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\cursor_cext.py”,第 248 行 准备 = self._cnx.prepare_for_mysql(params) 文件“C:\Users\AlexJ\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection_cext.py”,第 538 行,在 prepare_for_mysql raise ValueError("无法处理参数") ValueError: 无法处理参数

【问题讨论】:

  • 我很确定 MySQL 要求 %s 用单引号括起来。此外,您将遇到绑定问题,因为字符串将被解包。将("test") 更改为("test",),注意逗号
  • 为什么需要在元组尾随逗号?当我尝试在没有它的情况下执行查询时,它会失败。如果我添加尾随逗号,它会起作用。我不明白这有什么影响。当我在 Python 解释器中键入以下内容时,它们看起来是相同的:>>> (1, 2) == (1, 2,) True

标签: python mysql mysql-connector-python


【解决方案1】:

试试这个:

for x in data:
    value = "test"
    query = "INSERT INTO test (serial) VALUES (%s)"
    cursor.execute(query,(value,))
    print("Inserted",cursor.rowcount,"row(s) of data.")

由于您使用的是 mysql 模块,cursor.execute 需要一个 sql 查询和一个元组作为参数

【讨论】:

  • insertion 是一个语句,所以变量名query 不正确。
  • 非常感谢您的回答。通常的参考文档来源都没有提到这一点。
【解决方案2】:

@lucas 的回答很好,但也许这对其他人有帮助,因为我觉得更干净

sql = "INSERT INTO your_db (your_table) VALUES (%s)"
val = [("data could be array")]
cursor = cnx.cursor()
cursor.execute(sql, val)
print("Inserted",cursor.rowcount,"row(s) of data.")
cnx.commit()
cnx.close()

Cz 这对我的目的很有用,可以输入多个数据。

【讨论】:

    猜你喜欢
    • 2015-09-13
    • 2021-08-22
    • 2022-12-11
    • 1970-01-01
    • 2014-12-22
    • 2019-08-06
    • 2017-09-22
    • 1970-01-01
    相关资源
    最近更新 更多