Pass column name as parameter to PostgreSQL using psycopg2

前端 未结 2 1915
日久生厌
日久生厌 2020-12-11 00:50

I\'m trying to add columns to a table using psycopg2

row1 below is a list of column names to be added to the table. I can do it manually bu

2条回答
  •  -上瘾入骨i
    2020-12-11 01:37

    You cannot use SQL parameters for SQL object names. SQL parameters quote values explicitly so that they cannot be interpreted as such; that is one of the major reasons to use SQL parameters otherwise.

    You'll have to use string interpolation here. Be extremely careful that you are not using user input to produce c here:

    for c in row1:
        cur.execute("ALTER TABLE HHV2PUB ADD COLUMN %s text" % c)
    

    Psycopg2 does give you a method to mark parameters as 'already escaped' with psycopg2.extensions.AsIs(), but the intention is for this to be used on already escaped data instead.

    A much better idea is to use the psycopg2.sql extension to manage correct identifier escaping:

    from psycopg2 import sql
    
    for c in row1:
        cur.execute(
            sql.SQL("ALTER TABLE HHV2PUB ADD COLUMN {} text").format(
                sql.Identifier(c)))
    

提交回复
热议问题