加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

sqlie3 Replace into

发布时间:2020-12-12 19:37:29 所属栏目:百科 来源:网络整理
导读:在数据库表中,如果想某个字段相同的时候,只是更新该条记录而不是再次插入新纪录? 你会怎么办? 你会说,先 query 有没有,有的话就 update,没有就 insert. 这种方式也是也可的. 但是今天,介绍另一种方式, 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 的时候指定唯一索引.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读