0

我一直在搜索 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

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

4

1 回答 1

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] 你可以用*操作符来做,但这可能会让人感到困惑。

于 2017-03-07T16:39:37.140 回答