Answer the question
In order to leave comments, you need to log in
VALUES(?) how does it work in Sqlite3/Python?
I can't figure out how to use variables in queries to Sqlite3 database in Python3. Is it possible to use constructions with VALUES(?) after FROM (when the table name is taken from a variable), and after WHERE (when variables are compared with column values in conditions). In INSERT INTO - works, just inserts column values. And in the given simple request of sampling with a condition in any way. I do not want to believe that this is not implemented.
EXAMPLE:
table1 = "days"
yr="2022"
d="1"
m="1"
cur.execute("""SELECT ym1, ym2 FROM (VALUES(?)) WHERE (year = VALUES(?)) AND (month = VALUES(?)) AND (day = VALUES(?));""", (table1, yr, d, m))
Answer the question
In order to leave comments, you need to log in
While it was possible to substitute variables after WHERE.
SELECT ym1, ym2
FROM tablename WHERE (year = ?) AND (month = ?) AND (day = ?);""", (table1, yr, d, m)
PS In addition to forming a query as a string, and further use, how
cur.execute(sqlselect)
was an acceptable option using f-strings. Much more universal than "?" and all sorts of VALUES
table1 = "days"
yr="2022"
d="1"
m="1"
cur.execute(
f"SELECT ym1, ym2 FROM {table1} WHERE year = ? AND month = ? AND day = ?;",
(table1, yr, d, m)
)
1. VALUES is part of the SQL syntax, more precisely the INSERT query, and not the sqlite3 python wrapper. Your request is syntactically incorrect. The wrapper only allows you to replace the token ? to the passed value.
2. As far as I know, it is impossible, since value substitution can only insert constants - numbers and strings. You can (just be careful) use regular string formatting. But in general, if you stumble upon such a task, you should stop and ask yourself again: is it possible to achieve the same result in a different way? Because in the dynamic formation of SQL queries it is easy to screw up.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question