I have been searching through Stack Overflow as well as some other online research looking for the correct syntax to insert variables into my SQLite query. However, none of the 3 supported syntaxes have worked for my queries.
I found that the three supported syntaxes for the SQLite DB-API are:
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"})
taken from http://www.philvarner.com/test/ng-python3-db-api/
However when I execute the following, I receive these errors:
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
Please provide any insight you may have on this issue.
So your fundamental issue is simply one of syntax. Defining tableListQuery
as "my query string", params
defines a tuple; you can't pass that tuple directly to execute
, and the documentation does not say you can.[1]
You need to do as shown in the original snippet you quoted:
tableListQuery = "SELECT name FROM table WHERE type=:dbFile ORDER BY Name"
params = {'dbFile': dbFile}
userCursor.execute(tableListQuery, params)
Now the second issue, as pointed out in the comments, is that you can't use SQL parameters for things like field or table names; only for WHERE values. You would need to use normal Python string formatting for that.
[1] You could do it with the *
operator, but that's probably confusing at this point.