Python MYSQL动态查询:将值插入表语法

2024-10-02 20:39:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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

有人知道正确的语法吗? 提前谢谢


Tags: executemysql语法动态conncursorcommitinsert
1条回答
网友
1楼 · 发布于 2024-10-02 20:39:23

您的查询不正确,因为列的名称与您尝试插入的值不对应。 假设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)

其中column1column2是要插入的列的名称。 因此,正确的方法是:

 select5 = """ INSERT INTO oldcards (column1, column2) VALUES (%s, %s); """
 tple = (str(RouteID),str(mydict[ID1]["Card1"]))
 cursor.execute(select5,tple)
 conn.commit()

相关问题 更多 >