2016-02-11 39 views
0

我有一個查詢,我想追加到一個文件(以生成一個查詢列表),稍後將執行。如何獲得消毒postgres SQL字符串在Python中供以後使用?

location_filter="SELECT id FROM developers WHERE location='%s'" 
out_file.write((location_filter, (location))) 

但是,被寫入輸出不能在pgAdmin的執行:

("SELECT id FROM developers WHERE location='%s'", u'Seattle') 

我怎樣才能安全地產生這種說法?

回答

1
conn = psycopg2.connect(database='cpn') 
cur = conn.cursor() 

location_filter = "SELECT id FROM developers WHERE location = %s" 
out_file.write(cur.mogrify(location_filter, (location,)))