我正在使用Python和mysql(导入mysql连接器)。
我试图在一个动态列中插入多个值,这是我之前创建的。 但是,我的查询的语法被搞乱了,我无法正确地编写它。
正在工作的是什么(例如不是动态的):->; 在列ynoqxzvb中,添加值'1C'。
conn.cursor()
select4 = """ INSERT INTO oldcards (ynoqxzvb) VALUES ('1c'); """
cursor.execute(select4)
conn.commit()
我要做的是(动态):
select5 = """ INSERT INTO oldcards (%s) VALUES (%s); """
tple = (str(RouteID),str(mydict[ID1]["Card1"]))
cursor.execute(select5,tple)
conn.commit()
所以基本上,我希望使用本地变量“routeid”和“str(mydict[ID1][”card1“])”使columnname和插入值动态。
错误代码为:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ynoqxzvb') VALUES ('Card2=4b')' at line 1
有人知道正确的语法吗? 提前谢谢!
您的查询不正确,因为列的名称与您尝试插入的值不对应。 假设str(RouteID)
为1,str(mydict[ID1][“card1”]
为2.则Cursor.execute(select5,tple)
将查询转换为
INSERT INTO oldcards (1) VALUES (2)
你实际上想要的是:
INSERT INTO oldcards (column1, column2) VALUES (1,2)
其中column1
和column2
是要插入的列的名称。 所以正确的方法是:
select5 = """ INSERT INTO oldcards (column1, column2) VALUES (%s, %s); """
tple = (str(RouteID),str(mydict[ID1]["Card1"]))
cursor.execute(select5,tple)
conn.commit()