我正在使用python sql编辑一个名为
students
(其列为
name
和
age
,如下所示:
('Rachel', 22)
('Linckle', 33)
('Bob', 45)
('Amanda', 25)
('Jacob', 85)
('Avi', 65)
('Michelle', 45)
我正在定义python函数来执行SQL代码。
在我的第一个函数中,我想更新
年龄
价值观
学生
表在哪里
名称
与某物(例如Bob)匹配。如果我定义以下函数:
def update_age(age, name):
c.execute("""UPDATE students SET age = %s
WHERE name = %s""", (age, name))
然后:
update_age(99, 'Bob')
我会得到:
('Rachel', 22)
('Linckle', 33)
('Bob', 99)
('Amanda', 25)
('Jacob', 85)
('Avi', 65)
('Michelle', 45)
在第二个函数中,我还想指定表的名称,代码如下:
def update_age_table(table, age, name):
c.execute("""UPDATE %s SET age = %s
WHERE name = %s""",
(table, age, name)) # note that here I am only replacing students by the placeholder %s
如果我这样做:
update_age_table(table='students', age=95, name='Jacob')
我将收到以下错误消息(它很长,我只显示最后一句话:
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 ''students' SET age = 95
WHERE name = 'Jacob'' at line 1
我想这个错误是因为我
指派
变量的两个占位符,即
年龄
和
名称
,而不是表名的情况,其中没有变量赋值。
有人知道如何在不将占位符分配给变量的情况下使用SQL命令中的占位符吗?