Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
763 views
in Technique[技术] by (71.8m points)

android - Can we use Guid as a Primary Key in Sqlite Database

Is is possible to use GUID as primary Keys in SQLITE Database?If Possible which datatype can be used?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

SQLite itself does not support GUID as internal type.

Except that, it does! (sort of). Remember, in SQLite any string can be used as type name, and that includes GUID or UUID (read more about SQLite datatypes).

According to those rules, GUID type has affinity NONE, which is the same as for BLOB fields. With this in mind, you can create column of GUID type, and use following rules to access it:

  • Store it as string like X'01020304050607080910111213141516' (X notation is used to represent 16 byte BLOB value). To insert, use:

    INSERT INTO mytable (uuid)
    VALUES (X'01020304050607080910111213141516');
    
  • Read it as 16-byte BLOB. quote(uuid) can be used to format output using X notation:

    SELECT quote(uuid)
    FROM mytable
    

Such column can be also used as primary key. Unfortunately, there is no AUTOINCREMENT functionality like it exists for integer primary keys - you will have to handle it yourself. You can use something as simple as randomblob(16) for that, but it is not quite UUID as defined by standard.

Confusingly, you can also store text representation of UUID in the same field (SQLite won't stop you from doing that), but it will take at least 2x more space: BLOB is 16 bytes, UUID as text is at least 32 bytes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...