我想知道执行 MySQL 替换与执行更新或插入语句的优点/缺点是什么。
基本上,
做
dao.replaceEntry(entry);
代替:
if(existing){
dao.insertEntry(entry);
} else {
dao.updateEntry(entry);
}
此外,调用 dao.replaceEntry 调用 dao.insertOrUpdate 是否会产生误导?
最佳答案
我会执行 insertOrUpdate 而不是替换。根据 Mysql 的文档
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted
如果该行存在,它将执行删除,然后插入新行。更新是执行此操作的更好方法,然后像 REPLACE 所做的那样删除和插入,即一个操作与两个操作。
我能想到的另一个问题是在数据库中有触发器或级联删除。与 REPLACE 的情况一样,您会介意最终删除相关行,因为 REPLACE 将首先删除,然后在具有相同 ID 的行已存在时插入。
关于java - SQL 替换与执行插入或更新语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3752603/