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 ?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

AsIs should not be used for this purpose, the new sql module should be used instead: stackoverflow.com/a/42980069/5285608
@AntoineDusséaux: Agreed. The new sql module provides a much cleaner method for composing dynamic queries. I've updated the old answer accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.