bri*_*isk 2 python mysql sql mysql-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,))
Run Code Online (Sandbox Code Playgroud)
MySQL有REPLACE 声明:
REPLACE的工作方式与完全相同INSERT,不同之处在于,如果表中的旧行与aPRIMARY KEY或UNIQUE索引的新行具有相同的值,则在插入新行之前删除该旧行。
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,)
)
Run Code Online (Sandbox Code Playgroud)
更新根据@ Yo-han的评论,REPLACE就像DELETE和INSERT,不是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))
Run Code Online (Sandbox Code Playgroud)