How to use passed parameter as table Name in Selec

2019-08-13 03:56发布

问题:

i have the following function which extracts data from table, but i want to pass the table name in function as parameter...

def extract_data(table):
    try:
        tableName = table
        conn_string = "host='localhost' dbname='Aspentiment' user='postgres' password='pwd'"
        conn=psycopg2.connect(conn_string)
        cursor = conn.cursor()    
        cursor.execute("SELECT aspects_name, sentiments FROM ('%s') " %(tableName))
        rows = cursor.fetchall()
        return rows
    finally:
        if conn:
            conn.close()

when i call function as extract_data(Harpar) : Harpar is table name but it give an error that 'Harpar' is not defined.. any hepl ?

回答1:

Update: As of psycopg2 version 2.7:

You can now use the sql module of psycopg2 to compose dynamic queries of this type:

from psycopg2 import sql
query = sql.SQL("SELECT aspects_name, sentiments FROM {}").format(sql.Identifier(tableName))
cursor.execute(query)

Pre < 2.7:

Use the AsIs adapter along these lines:

from psycopg2.extensions import AsIs
cursor.execute("SELECT aspects_name, sentiments FROM %s;",(AsIs(tableName),))

Without the AsIs adapter, psycopg2 will escape the table name in your query.