在数据库表中, 如果想某个字段相同的时候, 只是更新该条记录而不是再次插入新纪录?
你会怎么办?
你会说, 先 query 有没有, 有的话就 update, 没有就 insert.
这种方式也是也可的.
但是今天, 介绍另一种方式, replace into.
--------------------------------------------------------------------------------------------------------------------
* 创建数据库文件
sqlite3 my.db
* 创建表
create table if not exists user (id integer primary key autoincrement, age integer, name text, uid long);
* 创建唯一索引
create unique index uid_index on user (uid);
使用 uid 作为唯一索引.
* 插入记录
replace into user (age, name, uid) values (20, 'makr', 1000);
此时可以查询一下记录
.header on
.mode column
select * from user;
id age name uid
---------- ---------- ---------- ----------
1 20 makr 1000
插入相同的 uid 记录
replace into user (age, name, uid) values (20, 'h', 1000);
得到结果
id age name uid
---------- ---------- ---------- ----------
2 20 h 1000
只是更新了 name 字段, 并没有新增记录.
细心的你可能已经发现, 主键自动加1了!
如果你使用 query->insert or update, 就不会发生主键自动加1的情况, 根据需要, 自己撸吧!
你也可以在 create table 的时候指定唯一索引.