Miroslav Georgiev
Miroslav Georgiev

Reputation: 25

How to use a parameter to select one or more columns in a SELECT statement

I'm trying to create a function that is able to select particular columns from a SQLite 3 table. The idea is to do something like this:

con = sqlite3.connect("my_db.db")
cursor = con.cursor()
def my_func(parameter_list):
    con.execute("SELECT parameter_list FROM a_table")
    return cursor.fetchall()

where the parameter_list contains the names of the columns the user wants selected.

I've tried using ? placeholders, but:

  1. I still need to use a fixed amount in the SELECT statement itself;
  2. for some reason the output is the names of the columns, not the contents. What I want to do is let the user determine the number of columns and which columns exactly he'd like to fetch.

Upvotes: 1

Views: 132

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46899

you need to get a comma-separated string for the columns, right? can be done like his:

"SELECT {} FROM a_table".format(','.join(parameter_list))

Upvotes: 2

Related Questions