2016-02-11 78 views
1

我有以下功能,從表中提取數據,但我想在功能參數傳遞的表名...如何使用傳遞參數作爲表名Select in query python?

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() 

當我打電話功能extract_data(Harpar):Harpar是表名 但它給出了一個錯誤,'Harpar'沒有被定義..任何hepl?

回答

1

更新:由於psycopg2 2.7版:

您現在可以使用psycopg2的SQL模塊組成這種類型的動態查詢:

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

前< 2.7

沿着這些線使用AsIs適配器:

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

沒有AsIs適配器,psycopg2將在您的查詢中轉義表名。

+1

'AsIs'不應該用於這個目的,應該使用新的'sql'模塊來代替:http://stackoverflow.com/a/42980069/5285608 –

+1

@AntoineDusséaux:同意。新的sql模塊提供了一個更簡潔的方法來編寫動態查詢。我已經相應地更新了舊的答案。 – Noyer282

相關問題