如何在MySQL Python中执行upsert(更新和插入)查询?

如何在MySQL Python中执行upsert(更新和插入)查询?,python,mysql,sql,mysql-python,Python,Mysql,Sql,Mysql Python,我正在寻找一个简单的升级(更新/插入) 我有一个表,我在其中为books表插入行,但下次当我要插入行时,我不想再次插入该表的数据,只想用所需的列进行更新,如果不存在,则创建新行 如何在Mysql-python中实现这一点 cursor.execute("""INSERT INTO books (book_code,book_name,created_at,updated_at) VALUES (%s,%s,%s,%s)""", (book_code,book_name,curr_time,cur

我正在寻找一个简单的升级(更新/插入)

我有一个表,我在其中为books表插入行,但下次当我要插入行时,我不想再次插入该表的数据,只想用所需的列进行更新,如果不存在,则创建新行

如何在Mysql-python中实现这一点

cursor.execute("""INSERT INTO books (book_code,book_name,created_at,updated_at) VALUES (%s,%s,%s,%s)""", (book_code,book_name,curr_time,curr_time,))
MySQL有一个声明:

REPLACE
的工作原理与
INSERT
的工作原理完全相同,除非 对于
主键
唯一键
索引时,在插入新行之前删除旧行

更新根据@Yo han的评论,
替换
就像
删除
插入
,而不是
插入
。以下是使用以下选项的替代方案:


这不是一次突袭。这是一个删除和插入操作。若要执行upsert,您应该使用语法。@Yo han,谢谢您提供的信息。我根据你的评论更新了答案。
cursor.execute("""
    REPLACE INTO books (book_code,book_name,created_at,updated_at)
    VALUES (%s,%s,%s,%s)""",
    (book_code,book_name,curr_time,curr_time,)
)
cursor.execute("""
    INSERT INTO books (book_code,book_name,created_at,updated_at)
    VALUES (%s,%s,%s,%s)
    ON DUPLICATE KEY UPDATE book_name=%s, created_at=%s, updated_at=%s
""", (book_code, book_name, curr_time, curr_time, book_name, curr_time, curr_time))