2013-03-17 171 views
4

如果記錄已經存在或需要創建新記錄,我需要更新一行。我不明白在DUPLICATE KEY將使用MYSQLdb來完成此操作,但是我無法使其工作。我的代碼是下面更新或插入MySQL Python

 cursor = database.cursor() 
     cursor.execute("INSERT INTO userfan (user_id, number, round VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE user_id =%s, number=%s, round=%s", (user_id, number, round)) 
     database.commit() 

主鍵user_id說明

+0

在一般情況下,可以考慮使用'sqlalchemy' – 2013-03-17 20:00:29

+0

什麼是primay(或唯一的)表中的關鍵? – 2013-03-17 20:03:29

+0

表中的列是什麼?看起來你有'round'和'roun_id'。這是一個錯字還是這兩列嗎? – 2013-03-17 20:07:27

回答

14

甲括號中missiing。您也可以在聲明的ON DUPLICATE KEY UPDATE部分使用VALUES(column)

cursor = database.cursor() 
    cursor.execute(""" 
     INSERT INTO userfan 
      (user_id, number, round) 
     VALUES 
      (%s, %s, %s) 
     ON DUPLICATE KEY UPDATE 
              -- no need to update the PK 
      number = VALUES(number), 
      round = VALUES(round) ; 
        """, (user_id, number, round)  # python variables 
       ) 
    database.commit() 
+0

謝謝,我認爲這很簡單!還有一個問題,你知道是否有可能在你的答案中輸入多行代碼,否則我會得到非常長的代碼行..我使用eclipse .. – DavidJB 2013-03-18 00:10:23

+0

@john請參閱編輯。閱讀[Python字符串](http://docs.python.org/2/tutorial/introduction.html#strings) – 2013-03-19 01:13:51