sqlite - 将 sqlite.net "bigint"替换为自动增量主键约束的整数

标签 sqlite xamarin auto-increment portable-class-library sqlite.net

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

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

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

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

这个解决方案是有效的解决方案吗?这会带来什么样的麻烦?

最佳答案

来自 Datatypes In SQLite Version :

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

但是,这并不意味着具有 INTEGER 亲和性的列适合自动递增任务! 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.

SQLite 中 INTEGER 值 的最大大小为 8 字节(64 位,带符号的二进制补码),因此可以干净地映射到 .NET(或 Java)中的 long 值);该列是否声明为“INTEGER”(它必须用于自动递增列)或“BIGINT”并不重要。 (实际类型是 per value, not per column ;但是,自增/ROWID 值都将是整数。)

此外,SQLite 自动具有“记录/行标识符”,即使没有显式创建这样的列 - 这是“ROWID”列,可以作为 ROWID 访问,_ROWID_OID 除非被隐藏。参见 SQLite Autoincrement如果这是一个合适的选择,因为它改变了算法并删除了一些单调递增的保证:

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..

关于sqlite - 将 sqlite.net "bigint"替换为自动增量主键约束的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24095211/

相关文章:

vb.net - 什么是 NULL 值以及如何在 SQLite 中处理它们

c# - 使用数据库中的Reverse-LIKE进行选择

ios - Xamarin.IOS : Can't load image from Images. xcassets

android - 在外部应用程序中打开图像的内容提供者不起作用

postgresql - 将主键 int 类型更改为 serial

SQLite - 仅按年选择行?

node.js - 在为 Electron 构建 SQLite 模块后,如何修复这些运行时错误?

mysql - MySQL如何设置初值和自增?

android - 如何防止 SupportV4 (Fragment)Tabhost 在 TabChange 上创建自己的 Fragment?

MySQL - 无法将表的自动增量值设置为较低的值