我的问题是当我决定创建一种可以处理各种查询的方法而不是对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
之类的操作,然后执行(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
我的猜测是,您不能仅按列进行参数设置,因为您没有分配值(例如在where
或group by
中,您有一个赋值:{{ 1}} = whatever
)。
对此有何见解?我做了相当多的研究,但没有发现任何东西。 here提到了这一点。
如果您对这个问题有任何疑问,请问我,我会更加清楚!
答案 0 :(得分:2)
您无法参数化表名,只能使用列值来做到,所以您必须这样做:
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