mysql中表名的占位符

5uzkadbs  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(458)

我使用pythonsql来编辑一个非常简单的表,名为 students (其列是 name 以及 age ),如下图:

('Rachel', 22)
('Linckle', 33)
('Bob', 45)
('Amanda', 25)
('Jacob', 85)
('Avi', 65)
('Michelle', 45)

我正在定义python函数来执行sql代码。
在我的第一个函数中,我想更新 age 中的值 students table在哪里 name 匹配某物(如鲍勃)。如果我定义以下函数:

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

我猜这个错误是因为我给变量分配了两个占位符,即 age 以及 name ,这不是表名的情况,表名中没有变量赋值。
有人知道我如何在sql命令中使用占位符而不将它们赋给变量吗?

hsvhsicv

hsvhsicv1#

那个ś 因为在execute语句中不能将表名作为参数传递。你应该这样做:

def update_age_table(table, age, name):
    c.execute("UPDATE "+table+" SET age = %s
    WHERE name = %s", 
             (table, age, name)) #

prepared语句不适用于表名
编辑必须删除如下表参数:

def update_age_table(table, age, name):
    c.execute("UPDATE "+table+" SET age = %s WHERE name = %s",(age, name)) #

抱歉是个错误

相关问题