小编典典

MySQL Connector无法处理参数

python

我正在尝试遍历数组并将每个元素插入表中。据我所知,我的语法是正确的,我直接从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(...)然后失败。这是堆栈跟踪。

追溯(最近一次通话最近):在cursor.execute中,文件“ test.py”,第29行(“ INSERT INTO
test(序列)值(%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在Prepare_for_mysql中,\ AppData \ Local \ Programs \ Python \
Python37 \ lib \ site-packages \ mysql \ connector \
connection_cext.py“,行538引发ValueError(”无法处理参数“)ValueError:无法处理参数


阅读 262

收藏
2021-01-20

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

2021-01-20