UPDATE or INSERT MySQL Python

若如初见. 提交于 2019-12-06 01:50:29

问题


I need to update a row if a record already exists or create a new one if it dosen't. I undersant ON DUPLICATE KEY will accomplish this using MYSQLdb, however I'm having trouble getting it working. My code is below

        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()

primary key is user_id


回答1:


A parenthesis was missiing. You can also use the VALUES(column) in the ON DUPLICATE KEY UPDATE section of the statement:

    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()


来源:https://stackoverflow.com/questions/15465478/update-or-insert-mysql-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!