python - MySQL 连接器无法处理参数

标签 python mysql mysql-connector-python

我正在尝试遍历一个数组并将每个元素插入到一个表中。据我所知,我的语法是正确的,我直接从 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 (most recent call last): File "test.py", line 29, in 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", line 248, in 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", line 538, in prepare_for_mysql raise ValueError("Could not process parameters") ValueError: Could not process parameters

最佳答案

试试这个:

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

关于python - MySQL 连接器无法处理参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54518722/

相关文章:

python - GTK 对话框边距不起作用

php - 按日期排序 DESC d-m-Y

mysql - 使用 XPage Rest 服务连接到 mysql 时出错

python - mySQLdb 连接返回截断的输出

mysql - Python - Mac OSX 10.10 中的 MySQL 连接器错误

python - 双 for 循环到 Python 列表理解

python - 如何在 python 中验证日期字符串格式?

关闭控制台时出现 Python Matplotlib 运行时错误

python - 在 Django 中查找给定时间段内最新条目的更快方法

python - sqlalchemy 无法识别我的 mysql 数据库