博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Perform UPSERT / INSERT OR UPDATE against a SQLite Database
阅读量:6959 次
发布时间:2019-06-27

本文共 1928 字,大约阅读时间需要 6 分钟。

Option 1: You can afford deleting the row

In other words, you don't have foreign key, or if you have them, your SQLite engine is configured so that there no are integrity exceptions. The way to go is INSERT OR REPLACE. If you are trying to insert/update a player whose ID already exists, the SQLite engine will delete that row and insert the data you are providing. Now the question comes: what to do to keep the old ID associated?

Let's say we want to UPSERT with the data user_name="steven" and age=32.

Look at this code:

INSERT INTO players (id, name, age)VALUES(coalesce((select id from players where user_name="steven"),(select max(id)from drawings)+1),32)

The trick is in coalesce. It returns the id of the user "steven" if any, and otherwise, it returns a new fresh id.

 

Option 2: You cannot afford deleting the row

After monkeying around with the previous solution, I realized that in my case that could end up destroying data, since this ID works as a foreign key for other table. Besides, I created the table with the clause ON DELETE CASCADE, which would mean that it'd delete data silently. Dangerous.

So, I first thought of a IF clause, but SQLite only has CASE. And this CASE can't be used (or at least I did not manage it) to perform one UPDATE query if EXISTS(select id from players where user_name="steven"), and INSERT if it didn't. No go.

And then, finally I used the brute force, with success. The logic is, for each UPSERT that you want to perform, first execute a INSERT OR IGNORE to make sure there is a row with our user, and then execute an UPDATE query with exactly the same data you tried to insert.

Same data as before: user_name="steven" and age=32.

-- make sure it exists --INSERTOR IGNORE INTO players (user_name, age)VALUES("steven",32);-- make sure it has the right data --UPDATE players SET user_name="steven", age=32WHERE user_name="steven";

 

转载于:https://www.cnblogs.com/MinieGoGo/p/3448997.html

你可能感兴趣的文章
StratoIO WebPrinter控件的下载与安装的步骤介绍
查看>>
SSH隧道
查看>>
virtualbox设置ubuntu的共享目录
查看>>
安卓调用webservice的一种方式及需注意的问题
查看>>
DIY 微信HD版共享
查看>>
python入门(四)python对文件的操作
查看>>
C# 使用接口进行排序
查看>>
干货!APP推广全周期解决方案 只需做好这6步
查看>>
存储基础网络面临的几大问题
查看>>
高效|五大模式和两大创新,看懂智能制造具体呈现
查看>>
LNMP动态网站部署架构 Linux + Nginx 配置Nginx服务
查看>>
cai
查看>>
电力变压器胶模时要注意到哪几点问题?中港扬盛提醒
查看>>
Linux 高可用(HA)集群之keepalived详解
查看>>
parse AST with Clang-example
查看>>
面向切面编程(AOP模式)
查看>>
学java就两个问题
查看>>
asdasdas da
查看>>
文本三剑客grep、sed、awk
查看>>
双机热备软件
查看>>