3

我们将 sqlite 用于我们的移动项目 - 但是当我们尝试使用我们的长 id 变量作为主键自动增量时 - 代码给出错误“ Autoincrement is only allowed in integer primary key”。当我在网上查看这个错误时,我发现 sqlite 中的自动增量不允许用于bigint类型。

有趣的是它bigint也是由整数实现的——sqlite 没有bigint类型——它只是使用整数的大小来决定它是否为 a biginthttp://www.sqlite.org/datatype3.html

bigint为了解决这个问题 - 我用“ ”替换了创建表的开源代码integer,并编写了一些测试代码来验证它是否在常规整数的边界之外工作(添加了一个 id 大于整数范围的项目目的并不断添加10多个对象)。

看起来它现在正在工作 - 但我想知道它是否会导致其他一些问题。我们正在将移动应用程序 ID 同步到我们的数据库 ID,因此我们肯定会有大于正常整数范围的 ID。

这个解决方案是一个有效的解决方案吗?这会造成什么样的麻烦?

4

1 回答 1

3

From Datatypes In SQLite Version:

If the declared type contains the string "INT" then it is assigned INTEGER affinity.

However, this does not mean that a column with INTEGER affinity is suitable for auto-increment duty! The special case is explicitly drawn out in ROWIDs and the INTEGER PRIMARY KEY:

.. A PRIMARY KEY column only becomes an integer primary key if the declared type name is exactly "INTEGER". Other integer type names like "INT" or "BIGINT" or "SHORT INTEGER" or "UNSIGNED INTEGER" causes the primary key column to behave as an ordinary table column with integer affinity and a unique index, not as an alias for the rowid.

The maximum size of an INTEGER value in SQLite is 8 bytes (64bits, signed two's complement) and thus maps cleanly to a long value in .NET (or Java); it doesn't matter if the column was declared as "INTEGER", which it must be for an auto-increment column, or with "BIGINT". (The actual type is per value, not per column; however, auto-increment/ROWID values will all be integers.)

Also, SQLite automatically has a "record/row identifier", even without explicitly creating such a column - this is the "ROWID" column and can be accessed as ROWID, _ROWID_, or OID unless shadowed. See SQLite Autoincrement if this is a suitable option, as it changes the algorithm and removes some monotonically increasing guarantees:

These are important properties in certain applications. But if your application does not need these properties, you should probably stay with the default behavior since the use of AUTOINCREMENT requires additional work..

于 2014-06-07T08:34:41.680 回答