执行中的 Python sqlite3 字符串变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13880786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:49:30  来源:igfitidea点击:

Python sqlite3 string variable in execute

pythonsqlite

提问by Steffen

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

我尝试在 Python 中执行这个 sqlite3 查询。我将代码减少到最低限度,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.

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

采纳答案by CL.

Parameter markers can be used only for expressions, i.e., 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.)

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

回答by sdoering

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 几个星期了。

回答by Rajendra

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

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