0

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

asked Jul 5, 2013 at 15:29
4
  • 1
    I don't see the problem, the code is doing what is supposed to do. Be aware that you are returning the result of cur.execute sql query, and that is a tuple. Commented Jul 5, 2013 at 15:34
  • What examples in the docs? Commented Jul 5, 2013 at 15:41
  • It would appear I read the docs too quickly; select ? is present, but not select ? from .... Commented Jul 5, 2013 at 15:47
  • Also, thanks @ManuelGutierrez. I've added .fetchall() and edited the question. Commented Jul 5, 2013 at 16:02

1 Answer 1

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.

answered Jul 5, 2013 at 15:41
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.