I'm trying to put a column name into a SQL query thusly
import sqlite3
db = sqlite3.connect('path/to/my/database.sqlite')
cur = db.cursor()
def get_val(field):
return cur.execute('''
SELECT x, y, :field FROM literal_table
WHERE
:valid_field_name > 0 AND
(some other conditions)
GROUP BY x, y''',
{'field': field}).fetchall()
get_val('valid_field_name')
but when I execute the code, instead of grabbing the value from the column, python is returning
[(x1, y1, u'valid_field_name'), (x2, y3, u'valid_field_name'), ...]
I know that you can't encode table names, but there are examples in the docs of column names being parametrized. I've hacked together a solution with string formatting (the code's for private data processing, so SQL injection isn't a problem) but I need to understand what's going on!
I'm using Python 2.7.3
1 Answer 1
SQLite replaces parameters with the supplied values. In your case, this would be the same as:
SELECT x, y, 'valid_field_name' FROM literal_table
WHERE 'valid_field_name' > 0 AND (some other conditions)
GROUP BY x, y
In other words, strings are strings; it is not possible to have parameters as column names.
cur.executesql query, and that is a tuple.select ?is present, but notselect ? from ....