执行中的 Python sqlite3 字符串变量 [英] Python sqlite3 string variable in execute

查看:79
本文介绍了执行中的 Python sqlite3 字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在 Python 中执行这个 sqlite3 查询.我将代码减少到最少,sqlite.connect 等工作正常.

I try to execute this sqlite3 query in Python. I reduced the code to the minimum, sqlite.connect, etc works.

column = 'Pron_1_Pers_Sg'
goal = 'gender' 
constrain = 'Mann'


with con:
    cur = con.cursor()

    cur.execute("SELECT ? FROM Data where ?=?", (column, goal, constrain))
    con.commit()

    rows = cur.fetchall()

    for element in rows:
        values.append(element)

这将返回一个空列表.如果我对字符串进行硬编码,它将起作用并返回值.

This returns an empty list. If I hardcode the strings, it works and returns values.

推荐答案

参数标记只能用于表达式,即值.您不能将它们用于诸如表名和列名之类的标识符.

Parameter markers can be used only for expressions, i.e., values. You cannot use them for identifiers like table and column names.

使用这个:

cur.execute("SELECT "+column+" FROM Data where "+goal+"=?", (constrain,))

或者这个:

cur.execute("SELECT %s FROM Data where %s=?" % (column, goal), (constrain,))

(并且在您真正完成访问数据之前不要提交.)

(And don't commit before you have actually finished accessing the data.)

这篇关于执行中的 Python sqlite3 字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆