MySQL 连接器无法处理参数

MySQL Connector could not process parameters

我正在尝试遍历数组并将每个元素插入 table。据我所知,我的语法是正确的,我直接从 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 查询和一个元组作为参数

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