微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

sqlie3 Replace into

数据库表中,如果想某个字段相同的时候,只是更新该条记录而不是再次插入新纪录?

你会怎么办?

你会说,先 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,'h',1000);

得到结果
id          age         name        uid       
----------  ----------  ----------  ----------
2           20          h           1000   

只是更新了 name 字段,并没有新增记录.

细心的你可能已经发现,主键自动加1了!

如果你使用 query->insert or update,就不会发生主键自动加1的情况,根据需要,自己撸吧!


你也可以在 create table 的时候指定唯一索引.

原文地址:https://www.jb51.cc/sqlite/199253.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐