MySQL:Python中的参数化列名

MySQL:Python中的参数化列名,python,mysql,Python,Mysql,当我决定制作一个可以处理各种查询的方法,而不是编码3个方法时,我的问题就出现了。我想这样做是为了回收代码 我有这张桌子: (我是为了这个问题而创建的。您可以通过以下方式来完成: 因此:我试图参数化列名。我一直在where子句中这样做,但正如我前面提到的,我认为只使用一种方法(从id=%s的示例中选择%s)而不是3种不同的方法会更干净、更优化:(从etc中选择ex1,从etc中选择ex2) 所以我试了一下: 所以通常的方法是: def getex1(id): myCursor=mydb.

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

我有这张桌子:

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

因此:我试图参数化列名。我一直在
where
子句中这样做,但正如我前面提到的,我认为只使用一种方法(从id=%s的示例中选择%s)而不是3种不同的方法会更干净、更优化:(
从etc中选择ex1
从etc中选择ex2

所以我试了一下:

所以通常的方法是:

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
)的操作,然后通过
(query,input)
执行,所以我尝试了这样做,但使用了列名:

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

我的猜测是,您不能只按列执行参数,因为您没有赋值(例如在
where
group by
中,您有一个赋值:
无论什么
=

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


如果您发现这个问题有任何问题,请问我,我会说得更清楚!

您不能参数化表名,只能使用列值,因此您必须执行以下操作:

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
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
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