2012-07-27 44 views
0

這是我用來從讀取csv文件執行更新操作的python代碼。我也試用了this。它不工作。在python中更新查詢中定義參數psycopg2

for i in cin: 
    try: 
     conn=psycopg2.connect("dbname=pharmaflare user=postgres") 
     cursor=conn.cursor() 
     cursor.execute("UPDATE pharmaflare_drug_interaction SET se_interaction ='%s' WHERE primary_drug ='%s' AND secondary_drug ='%s' AND side_effect ='%s'"%(i[3],i[0],i[1],i[2])) 
     conn.commit() 
     cursor.close() 
     conn.close() 
     #print "done",i[0],i[1],i[2],i[3] 
    except Exception as e: 
     cerr.writerow(i) 
     ferr.flush() 
     traceback.print_exc(file=sys.stdout) 
     continue 

在這裏,我喜歡面對的語法錯誤之外,由於報價單的問題: 無論單引號呈現此異常出現。

Traceback (most recent call last): 
    File "<ipython console>", line 5, in <module> 
    ProgrammingError: syntax error at or near "S" 
    LINE 1: ...secondary_drug ='NEUER' AND side_effect ='MENIERE'S DISEASE' 

是否有其他方法可用來定義查詢語句而不會影響Quotes問題?

回答

0

有幾種方法可以解決它。簡單/黑客的方式是使用re.escape() function。這個功能可以被認爲是相當於PHP's addslashes() function,雖然它讓我很難做出這樣的比較。

話雖如此,我的閱讀表明psycopg2利用PEP 249。如果這是真的,那麼你應該能夠傳遞參數化查詢並且使其具有escape them for you

+0

永遠不要做「簡單/黑客方式」!將參數傳遞給psycopg2並讓它爲你逃脫。如果你試圖逃避它,你會做錯的。它在傳遞列表/元組/數組時很有用:'cursor.execute(「select * from mytable where number in%s and x =%s」,(tuple(1,2,3,4,5),'foo' ))' – AlbertFerras 2012-08-15 09:01:20

+0

噢,我同意 - 輕鬆/黑客的方式是警察出局,應該不惜一切代價避免。在這種情況下,它是爲了完整性而包含的。將參數傳遞爲PEP 249和您的註釋表明是解決此問題的正確方法。 – Thomas 2012-08-15 14:02:01