1

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.

1
  • I did a work around . columns = ['col1', 'col2', 'col3'] columnsstr = ','.join(map(str, columns )) querystring = 'SELECT ' + columnsstr + ' FROM %s ORDER BY timeentry ASC' cursor.execute(querystring %mytable) Commented Jun 14, 2018 at 8:21

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Very crisp and concise answer. Thank you.

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.