prototypus
prototypus

Reputation: 13

Python3 Trying to execute sql query with dynamic column names

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

Upvotes: 1

Views: 1639

Answers (2)

Rohan Kushwaha
Rohan Kushwaha

Reputation: 745

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)

Upvotes: 0

CL.
CL.

Reputation: 180162

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)

Upvotes: 2

Related Questions