Python sqlite3 string variable in execute

给你一囗甜甜゛ 提交于 2019-12-17 06:09:43

问题


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.


回答1:


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.)




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/13880786/python-sqlite3-string-variable-in-execute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!