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, name, uid) values (20, 'h', 1000);

得到结果

id          age         name        uid       
----------  ----------  ----------  ----------
2           20          h           1000   

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

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

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


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




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值