python - MySQL:Python 中的参数化列名称

标签 python mysql

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

我有这张表:

enter image description here

(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

我的猜测是您不能只按列执行参数,因为您没有分配值(例如在 wheregroup 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/

相关文章:

mysql - 使用sql查询基于mydb显示年龄范围

php - 在MySql中存储IPV6和IPV4,同样读取

python - TensorFlow:向 LSTM 添加正则化

python - 将参数作为用户输入的函数

c# - IronPython索引器参数编译错误

php - PHP 和 Mysql 脚本中哪一个更安全?

python - #!/bin/sh vs #!/usr/local/bin/python 在可执行文件中

Python:在对应的两个列表中找到最常见的元素

php - 尝试使用 php 检查 html 文本框是否为空

php - 延迟显示多个 Noty 通知