首页 > 解决方案 > MySQL:Python 中的参数化列名

问题描述

当我决定制作一种可以处理各种查询的方法而不是编写 3 种方法时,我的问题就来了。我想这样做是为了回收代码。

我有这张桌子:

在此处输入图像描述

(我是为了这个问题而创建的。您可以通过以下方式进行:

create table example (id int(1), ex1 varchar(15), ex2 varchar(15), ex3 varchar(15));
insert into example values(1, 'whatever11', 'whatever12', 'whatever13');
insert into example values(2, 'whatever21', 'whatever22', 'whatever23');
insert into example values(3, 'whatever31', 'whatever32', 'whatever33');

SO:我试图参数化列名。我一直在where子句中这样做,但正如我之前提到的,我认为只使用一种方法 ( select %s from example where id=%s) 而不是 3 种不同的方法会更清洁、更优化: ( select ex1 from etc, select ex2 from etc.

所以我尝试了这个:

所以正常的方法是这样的:

def getex1(id):
    myCursor=mydb.cursor()
    query='select ex1 from example where id=%s'
    myCursor.execute(query, (id,))
    result=myCursor.fetchone()[0]
    print(result) #prints 'whatever11 if id=1'

当我搜索如何进行参数化查询时,我看到要执行各种参数,您可以只执行类似的操作input=(param1, param2,然后执行 by (query, input),所以我尝试这样做,但使用列名:

在这里,信息是“ex1”、“ex2”或“ex3”:

def getAllFromExample(info, id):
    myCursor = mydb.cursor()
    query= 'select %s from example where id=%s'
    input = (info, id)
    myCursor.execute(query, input)
    result = myCursor.fetchone()[0]
    print(result) #in this case, prints the column names 'ex1', 'ex2', not the content

我的猜测是,您不能只按列执行参数,因为您没有分配值(例如在 awhere或 a 中group by,您有一个分配:whatever=value)。

对此有何见解?我做了相当多的研究,但没有发现任何东西。这里提到了这一点。

任何你觉得问题有问题的地方,都可以问我,我会说得更清楚!

标签: pythonmysql

解决方案


你不能参数化表名,你只能用列值来做,所以你必须这样做:

def getAllFromExample(info, DNI):
    myCursor = mydb.cursor()
    query= 'select '+info+' from example where id=%s'
    input = (id,)
    myCursor.execute(query, input)
    result = myCursor.fetchone()[0]
    print(result) #in this case, prints the column name

推荐阅读