当我决定制作一种可以处理各种查询的方法而不是编写 3 种方法时,我的问题就来了。我想这样做是为了回收代码。
我有这张表:
(I created it in the purpose of this question. You can do it by:
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'
当我搜索 how to do parameterized queries 时,我看到要执行各种参数,您只需执行 input=(param1, param2
之类的操作,然后执行 (query, input)
,所以我尝试这样做,但列名是:
here, info is 'ex1', 'ex2' or '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
中,你有一个分配:whatever
=value
).
对此有何见解?我做了很多研究,但没有找到任何东西。 here提到了这个。
如果您发现问题有任何问题,请问我,我会更清楚地说明!
最佳答案
你不能参数化表名,你只能用列值来做,所以你必须这样做:
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
关于python - MySQL:Python 中的参数化列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55099187/