首页 > 解决方案 > PostgreSQL SELECT column names programmatically in python

问题描述

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.

标签: pythonpostgresqlpsycopg2

解决方案


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.


推荐阅读