Assuming I have a database with table users
with a row:
ID = 0, name = 'myName'
I can get the ID value (assuming I'm connected) by using either:
cursor.execute("""SELECT ID FROM users WHERE %s = %s""" % ('name', 'myName'))
print(cursor.fetchone())
or
cursor.execute("""SELECT ID FROM users WHERE {} = {}""".format('name', 'myName'))
print(cursor.fetchone())
which both work perfectly fine but are bad practice according to the documentation.
The documentation suggest using either qmark or named style for queries with variable input. The problem arises when using the suggested styles in a SELECT * FROM myDatabase WHERE ? = ?
query.
qmark style:
cursor.execute("""SELECT ID FROM users WHERE ? = ?""", ('name', 'myName'))
print(cursor.fetchone())
named style
cursor.execute("""SELECT ID FROM users WHERE :column = :cell""", {'column': 'name', 'cell':'myName'})
print(cursor.fetchone())
Using either of the latter styles results in a None
returned. When using the qmark or named style in the context of INSERT
such as used in the example in the documentation it does work as expected.
(To clarify, with the qmark style, adding parentheses to each ?
or the entire ? = ?
does not change the outcome. Using parentheses with each ?
and using an additional argument causes execute()
to malfunction due to too many arguments given.)
What causes this behaviour? Is it possible to use qmark or named style in a SELECT...WHERE ? = ?
query?