[英]Python - MYSQL dynamic query: Insert values into table syntax
我正在使用 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"])”来动态化列名和插入值。
错误代码是:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.