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?
'AsIs'不应该用于这个目的,应该使用新的'sql'模块来代替:http://stackoverflow.com/a/42980069/5285608 –
@AntoineDusséaux:同意。新的sql模块提供了一个更简洁的方法来编写动态查询。我已经相应地更新了旧的答案。 – Noyer282