1

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 ?

nizam uddin
  • 341
  • 2
  • 6
  • 15

1 Answers1

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.

Noyer282
  • 934
  • 7
  • 18
  • 1
    `AsIs` should not be used for this purpose, the new `sql` module should be used instead: http://stackoverflow.com/a/42980069/5285608 – Antoine Dusséaux Mar 24 '17 at 09:14
  • 1
    @AntoineDusséaux: Agreed. The new sql module provides a much cleaner method for composing dynamic queries. I've updated the old answer accordingly. – Noyer282 Mar 24 '17 at 15:38