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

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

我有要在其中插入书表行的表,但是下次当我要插入行时,我不想再次为该表插入数据,只是想用必需的列更新(如果不存在则退出),然后创建新行。

如何在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,))

python大神给出的解决方案

MySQL具有REPLACE 语句:

REPLACE的工作原理与INSERT完全相同,不同之处在于,如果
表具有与PRIMARY KEYUNIQUE的新行相同的值
索引,则在插入新行之前删除旧行。

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

更新根据@ Yo-han的评论,REPLACE类似于DELETEINSERT,而不是UPSERT。这是使用INSERT ... ON DUPLICATE KEY UPDATE的替代方法:

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