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