简体   繁体   English

执行中的 Python sqlite3 字符串变量

[英]Python sqlite3 string variable in execute

I try to execute this sqlite3 query in Python.我尝试在 Python 中执行这个 sqlite3 查询。 I reduced the code to the minimum, sqlite.connect, etc works.我将代码减少到最低限度,sqlite.connect 等工作正常。

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, ie, values.参数标记只能用于表达式,即值。 You cannot use them for identifiers like table and column names.您不能将它们用于诸如表名和列名之类的标识符。

Use this:用这个:

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

or this:或这个:

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

(And don't commit before you have actually finished accessing the data.) (并且在您真正完成访问数据之前不要提交。)

试试这个: c.execute("SELECT {idf} FROM Data WHERE {goal}".\\ format(idf=column, goal=constrain))

I was having quite a similar problem today.我今天遇到了类似的问题。 I am not sure, if this might solve your problem:我不确定,这是否可以解决您的问题:

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

Important is the last ,重要的是最后

Give it a try, this was the problem with my code - so maybe it helps you too.试一试,这是我的代码的问题 - 所以也许它对你也有帮助。 Sorry, for not being able to really explain why, as I am just learning myself and am into python/sqlite for some weeks.抱歉,无法真正解释原因,因为我只是在学习自己,并且已经使用 python/sqlite 几个星期了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM