0

I have a table with three columns, cell, trx and type. This is the query I'm trying to run:

db.execute("SELECT cell,trx FROM tchdrop").fetchall()

It gives the correct output.

However when I try a = ("cell", "trx") and then

db.execute("SELECT ?,? FROM tchdrop", t).fetchall()

the output is [(u'cell', u'trx'), (u'cell', u'trx')] (which is wrong)

I'm doing this to figure out how to extract columns dynamically which is a part of a bigger problem.

Björn Pollex
77.2k30 gold badges206 silver badges290 bronze badges
asked Mar 10, 2011 at 10:51

2 Answers 2

3

The place holder (?) of python DB-API (like sqlite3) don't support columns names to be passed, so you have to use python string formatting like this:

a = ("cell", "trx")
query = "SELECT {0},{1} FROM tchdrop".format(*a)
db.execute(query)

EDIT:

if you don't know the length of the columns that you want to pass , you can do something like this:

a = ("cell", "trx", "foo", "bar")
a = ", ".join(a)
query = "SELECT {0} FROM tchdrop".format(a)
# OUTPUT : 'SELECT cell, trx, foo, bar FROM tchdrop'
db.execute(query)
answered Mar 10, 2011 at 10:55
Sign up to request clarification or add additional context in comments.

1 Comment

then, what do I do if I don't know the length of a?
0

The library replaces the specified values ("cell", "trx") with their quoted SQL equivalent, so what you get is SELECT "cell", "trx" FROM tchdrop. The result is correct.

What you are trying to achieve is not possible with the ? syntax. Instead, do string replacement yourself. You can check column names with regular expressions (like ^[a-zA-Z_]$) for more security.

For example:

columns = ",".join(("cell", "trx"))
db.execute("SELECT %s FROM tchdrop" % columns).fetchall()
answered Mar 10, 2011 at 10:56

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.