MySQL 连接器无法处理参数

新手上路,请多包涵

我试图遍历一个数组并将每个元素插入到一个表中。据我所知,我的语法是正确的,而且我直接从 Microsoft Azure 的文档 中获取了这段代码。

 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(...) 然后失败。这是堆栈跟踪。

回溯(最近调用最后):文件“test.py”,第 29 行,在 cursor.execute(“INSERT INTO test (serial) VALUES (%s)”,(“test”)) File “C:\Users\ AlexJ\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\cursor_cext.py”,第248行,在execute prepared = self._cnx.prepare_for_mysql(params) File “C:\Users\AlexJ \AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection_cext.py”,第 538 行,在 prepare_for_mysql 中 raise ValueError(“Could not process parameters”) ValueError: Could not process parameters

原文由 ajjohnson190 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 510
2 个回答

尝试这个:

 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 查询和一个元组作为参数

原文由 Lucas Hort 发布,翻译遵循 CC BY-SA 4.0 许可协议

@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 这对我的目的很有用,可以输入多个数据。

原文由 Budi Mulyo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题