SQLite DB-API 语法问题 Python 3.5

SQLite DB-API syntax issues Python 3.5

我一直在搜索 Stack Overflow 以及其他一些在线研究,寻找将变量插入到我的 SQLite 查询中的正确语法。但是,3 种支持的语法中的 none 对我的查询有效。

我发现 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

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

所以你的根本问题只是语法之一。将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 参数来表示字段或 table 名称;仅适用于 WHERE 值。为此,您需要使用正常的 Python 字符串格式。

[1] 您可以使用 * 运算符来完成,但此时可能会造成混淆。