2016-11-10 61 views
0

在以下代碼中,我想要插入authors,方法是找到link。遇到如何使用python將這些數據插入到postgresql中?

self.cur.execute(""" 
    UPDATE articles 
    SET authors = %s 
    WHERE link = %s returning id; 
""" % (authors, link)) 
ret_id = self.cur.fetchone() 

兩個問題:

  1. 有些名字是不是經常這樣的:

    LINE 1: UPDATE articles SET authors = Francesco D'Angelo, Roberto T... 
    
  2. 當作者姓名都沒有問題:

    """UPDATE articles SET authors = %s WHERE link = %s returning id;""" % (authors, link)) 
    psycopg2.ProgrammingError: syntax error at or near ":" 
    LINE 1: ...DATE articles SET authors = test WHERE link = http://www.wor... 
    

回答

1

當您使用SQL不要%格式化字符串,讓司機做適當的轉義:

self.cur.execute(
    """UPDATE articles SET authors = %s WHERE link = %s returning id;""", (authors, link)) 

通知我傳遞的數據作爲第二個參數,execute會採取逃避的數據的護理正常。

相關問題