2016-02-11 82 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

相关问题