How to use passed parameter as table Name in Select query python?

给你一囗甜甜゛ 提交于 2019-12-24 15:51:40

问题


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.



来源:https://stackoverflow.com/questions/35347625/how-to-use-passed-parameter-as-table-name-in-select-query-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!