Reputation: 13
I would like to pass programmatically few columns from python(psycopg2) in a table.
cursor.execute("SELECT col1,col2,col3...coln FROM %s ORDER BY datetime ASC" %mytable)
column name col1,col2,col3...coln can be of length 100's and change every time cursor.execute() is called.
Upvotes: 1
Views: 656
Reputation: 1723
You're already using string interpolation, so you could do the same for the column names. Put your column names in an array and join them when formatting the query:
columns = ['col1', 'col2', 'col3']
cursor.execute("SELECT %s FROM %s ORDER BY datetime ASC" % (','.join(columns), mytable))
It is important that the columns are strictly controlled by you and not generated from user input, as that would enable SQL injection attacks.
Upvotes: 1