python - 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
)。
对此有何见解?我做了相当多的研究,但没有发现任何东西。这里提到了这一点。
任何你觉得问题有问题的地方,都可以问我,我会说得更清楚!
解决方案
你不能参数化表名,你只能用列值来做,所以你必须这样做:
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
推荐阅读
- php - Doctrine 有没有办法让父母和孩子拥有相同的父母约束?
- api - 如何获取有关 Netflix、Primevideo 等各种流媒体服务的系列剧集的 url 路由?
- linux-kernel - 没有边缘 sysfs 的 gpio 引脚的用户空间中断
- python - 如何访问嵌套字典
- python - 在 Python 中将 html 表转换为图像(其他解决方案不起作用)
- html - 我有一个数据表,但不是在操作列上显示两个按钮,而是显示 HTML 代码,所以问题出在哪里
- c++ - return 语句如何在递归中工作?
- asp.net - 能否使用 ITfoxtec SAML 2.0 继续登录 Azure 中的示例项目?
- java - 我无法将图像和字体加载到我的包中(Java)
- sql-server - 使用 Typeorm 连接到 Nestjs 中的 mssql,但 Nest 无法解析 EmployeeRepository 的依赖关系