简体   繁体   English

无法将数据从Python列表插入SQL

[英]Cannot insert data from Python List into SQL

I get this error when I run the script bellow, I am able to connect to Instagram API and to print nr of followers: mysql.connector.errors.InterfaceError: Failed executing the operation; 我在以下脚本中运行时出现此错误,我能够连接到Instagram API并打印nr的关注者:mysql.connector.errors.InterfaceError:执行操作失败; Could not process parameters 无法处理参数

followers = str(followers)
followersdata = [followers]



conn = mysql.connector.connect(user='root', password='XXX',
                              host='127.0.0.1',
                              database='InstagramStore')

cursor = conn.cursor()

q = """INSERT INTO InstagramFollowers (followers) VALUES (%s)"""

cursor.executemany(q, followersdata)
conn.commit() 

You can insert into multiple values in one execute with giving a list into execute command. 您可以在一次执行中插入多个值,只需在执行命令中给出一个列表即可。 The problem is in query. 问题出在查询中。

First you should format your query via 首先,您应该通过以下方式设置查询格式

query = """INSERT INTO InstagramFollowers {0} VALUES ({1})""".format(followers, values)

Then you should give your values in a list 然后,您应该在列表中给出您的值

cursor.execute(query, list)

You have your query incorrectly formatted. 您的查询格式错误。 I didnt know what the second %s stood for in your query, so I just used the variable values to hold its place. 我不知道第二个%s在查询中代表什么,所以我只是使用变量values来保持它的位置。

It should look more like: 它看起来应该更像:

Python <2.6 Python <2.6

q = """INSERT INTO InstagramFollowers (%s) VALUES (%s)""" (followers, values)

Python >2.6 Python> 2.6

q = """INSERT INTO InstagramFollowers {0} VALUES {1}""".format(followers, values)

Python >3.6 Python> 3.6

q = f"""INSERT INTO InstagramFollowers {followers} VALUES {values}"""

You can use convert the list to json and write the json into the table. 您可以使用将列表转换为json并将json写入表中。

INSERT INTO InstagramFollowers(followers) VALUES(json.dumps(followersdata))

This should work. 这应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM