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

不建议使用rowid作为sqlite主键

发布时间:2020-12-12 19:57:25 所属栏目:百科 来源:网络整理
导读:If you don’t want to read the whole post then just do this: Everytime you create a table with sqlite make sure to havean INTEGER PRIMARY KEY AUTOINCREMENT column (the rowid columnwill be an alias to this one). If you have some time then r

If you don’t want to read the whole post then just do this: Everytime you create a table with sqlite make sure to haveanINTEGER PRIMARY KEY AUTOINCREMENTcolumn (the rowid columnwill be an alias to this one).

If you have some time then read on…

A lot of people don’t realize thata rowidcan change. As always a simple example worths more than1000 words. You can test this example withSQLiteManager.

Create a table without a primary key:
CREATE TABLE test (name TEXT);

Insert some data into the table:
INSERT INTO test (name) VALUES (‘marco’);
INSERT INTO test (name) VALUES (‘giuly’);
INSERT INTO test (name) VALUES (‘gregory’);
INSERT INTO test (name) VALUES (‘house’);

Perform a SELECT rowid,* FROM test;
Here you go the result:
1marco
2giuly
3gregory
4house

Everything seems OK (until now…)
Now delete a couple of rows:
DELETE FROM test WHERE name=’marco’;
DELETE FROM test WHERE name=’gregory’;

Now perform again: SELECT rowid,* FROM test;
Here it is the result:
2giuly
4house

Everything is fine,no?
That’s cool…

Now,perform a VACUUM on the database and run again thequery:
SELECT rowid,* FROM test;
Here it is the result:
1giuly
2house

Rowids are changed!!!! So please take extra care when you define atable and need to reference records using rowids. From the official documentation: “Rowids can change at any time andwithout notice. If you need to depend on your rowid,make it anINTEGER PRIMARY KEY,then it is guaranteed not to change”. And Iadd also AUTOINCREMENT so you are sure that the same rowid(s) arenot reused when rows are deleted.

(编辑:李大同)

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

    推荐文章
      热点阅读