Python3 Trying to execute sql query with dynamic column names
Question: 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


Answer: 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)
    

