我通过阵列试图循环,每个元素插入表中。至于我可以看到我的语法是正确的,我把这个代码直接从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(...)
,然后失败。这里是堆栈跟踪。
回溯(最后最近一次调用):文件 “test.py”,第29行,在cursor.execute( “INSERT INTO测试(串行)VALUES(%S)”,( “测试”))文件“C:\用户\ AlexJ \应用程序数据\本地\程序\的Python \ Python37 \ lib中\站点包\ MySQL的\连接器\ cursor_cext.py “线路248,在执行准备= self._cnx.prepare_for_mysql(PARAMS)文件” C:\用户\ AlexJ \应用程序数据\本地\程序\ Python的\ Python37 \ LIB \站点包\ mysql的\连接器\ connection_cext.py”,线路538,在prepare_for_mysql提高ValueError异常( “无法处理参数”)ValueError异常:无法工艺参数
尝试这个:
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查询和一个元组作为参数