1

I am using sqlite3 and I am trying to dynamically return specific columns from database using SELECT query, problem is I keep getting the column names back instead of the actual rows. Here is an example code

import sqlite3
conn = sqlite3.connect('db_name.db')
c = conn.cursor()

query = 'SELECT ?, ? FROM devices'
columns = ('name','network-id')
c.execute(query, columns)

print(c.fetchall())

This is the result I get:

[('name', 'network_id'), ('name', 'network_id'), ('name',    'network_id'), ('name', 'network_id'), ('name', 'network_id'), ('name', 'network_id'), ('name', 'network_id'), ('name', 'network_id'), ('name', 'network_id')]

It is very annoying, I am only trying to get back specific columns from my results, but I get the column names instead. Any help will be much appreciated

1
  • in line 6 of the code it is actually 'network_id' Commented Jan 22, 2016 at 10:00

2 Answers 2

2

You cannot use SQL parameters for table or column names, only for literal values.

Your query is the equivalent of:

SELECT 'name', 'network-id' from devices

Just put the column names directly into the query:

columns = ('name','network-id')
query = 'SELECT %s from devices' % ','.join(columns)
Sign up to request clarification or add additional context in comments.

1 Comment

Much appreciated. I had no idea SQL parameters can only be used for literal values.
0

Use columns name, network-id in the SELECT query itself as follows:

query = 'SELECT name, network-id FROM devices'

? is used to relpace value in the query for example

query = 'SELECT name, network-id FROM devices where name = ?'
columns = ('my-name')
c.execute(query, columns)

Comments

Your Answer

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.