Search code examples
postgresqlflaskpsycopg2

Select from columns where column names are in list of strings


I'm using psycopg2, not sqlalquemy. Basically, I can pass parameters to other portions of query, except for the column name. I'm trying to query some columns in order for a particular row, where the column names are enumerated in a list. The problem is the postgres query doesn't work for column names as strings. Any suggestions as to how to approach this problem?

cols = ['first', 'second', 'third']
query = """
              SELECT %s FROM table_x
              WHERE year=2021;
        """
for c in cols:
     cur.execute(query, [c])
     print(cur.fetchone()[0])


Solution

  • Using sql module from psycopg2. An example that I believe is more on point and cleaner then the answer posted in the comment.

    import psycopg2
    from psycopg2 import sql 
    
    con = psycopg2.connect(dbname="test", host='localhost', user='postgres', port=5432)
    
    cols = ['first', 'second', 'third']
    
    qry = sql.SQL("SELECT {} FROM table_x WHERE year=2021").format(sql.SQL(", ").join(map(sql.Identifier, cols)))
    
    
    print(qry.as_string(con))                                                                                                                                                 
    SELECT "first", "second", "third" FROM table_x WHERE year=2021