SQLite DB-API语法问题Python 3.5

时间:2017-03-07 16:15:01

标签: python sqlite python-3.x python-db-api

我一直在搜索Stack Overflow以及其他一些在线研究,寻找将变量插入我的SQLite查询的正确语法。但是,3个支持的语法都没有适用于我的查询。

我发现SQLite DB-API支持的三种语法是:

qmark:
curs.execute("SELECT * FROM actors where actor.first_name = ?",("D'Angelo", ))

numeric:
curs.execute("SELECT * FROM actors where actor.first_name = :1", ("D'Angelo", ))

named:
curs.execute("SELECT * FROM actors where actor.first_name = :first_name",{'first_name': "D'Angelo"})

取自http://www.philvarner.com/test/ng-python3-db-api/

但是,当我执行以下操作时,我收到以下错误:

named:

tableListQuery = "SELECT name FROM :dbFile WHERE type='table' ORDER BY Name", {'dbFile': dbFile}
userCursor.execute(tableListQuery)

Pycharm error: Expected type 'str', got 'Tuple[str, Dict[str, Any]]' 

Terminal error:
File "./dedupeDatabase.py", line 15, in Describe
userCursor.execute(tableListQuery)
ValueError: operation parameter must be str
-------------------------------------------------
qmark:

tableListQuery = "SELECT name FROM ? WHERE type='table' ORDER BY Name", (dbFile, )
userCursor.execute(tableListQuery)

Pycharm error: Expected type 'str', got 'Tuple[str, Tuple[Any]]' instead

Terminal error:
File "./dedupeDatabase.py", line 15, in Describe
userCursor.execute(tableListQuery)
ValueError: operation parameter must be str
-------------------------------------------------
numeric:

tableListQuery = "SELECT name FROM :1 WHERE type='table' ORDER BY Name", (dbFile, )
userCursor.execute(tableListQuery)

Pycharm error: Expected type 'str', got 'Tuple[str, Tuple[Any]]'

Terminal error:
File "./dedupeDatabase.py", line 15, in Describe
userCursor.execute(tableListQuery)
ValueError: operation parameter must be str

请提供您对此问题的任何见解。

1 个答案:

答案 0 :(得分:2)

所以你的基本问题只是语法之一。将tableListQuery定义为"my query string", params定义元组;你无法将该元组直接传递给execute,文档也没有说你可以。[1]

您需要按照所引用的原始摘录中所示进行操作:

tableListQuery = "SELECT name FROM table WHERE type=:dbFile ORDER BY Name"
params = {'dbFile': dbFile}
userCursor.execute(tableListQuery, params) 

现在第二个问题,正如评论中指出的那样,你不能将SQL参数用于字段或表名之类的东西;仅适用于WHERE值。您需要使用普通的Python字符串格式。

[1]您可以使用*运算符执行此操作,但此时可能会感到困惑。