Skip to main content
 首页 » 编程设计

primary-key之SQLite 数据库创建时自动增量附近的语法错误

2024年05月29日30pengyingh

又是我,那个使用 SQLite-net 的人。当我的表主键上没有自动增量时,我的代码可以正常工作。我想自动增量键,所以我像这样重建了表:

using SQLite; 
 
namespace VehicleTracks.Models 
{ 
    public class vehicles 
    { 
        [PrimaryKey, AutoIncrement] 
        public int ID { get; set; } 
        public string VehID { get; set; } 
        public string VehYear { get; set; } 
        public string VehMake { get; set; } 
        public string VehModel { get; set; } 
        public string VehColor { get; set; } 
        public string EngineID { get; set; } 
        public System.DateTime PurchaseDate { get; set; } 
        public string SellerName { get; set; } 
        public string SellerStreet { get; set; } 
        public string SellerCityStateZip { get; set; } 
        public string VehOptions { get; set; } 
        public string OdomInitial { get; set; } 
        public string VehBodyStyle { get; set; } 
        public float PurchaseCost { get; set; } 
        public byte[] VehPhoto { get; set; } 
        public string VehType { get; set; } 
        public string Sold { get; set; } 
    } 
} 

现在,当尝试创建表时,我收到“自动增量附近的语法错误”。我尝试关闭 AutoIncrement,但如果没有它,它似乎不会增加 ID。

我可能错过了一些愚蠢的东西。

请您参考如下方法:

你的代码没有什么愚蠢之处;与 https://github.com/praeclarum/sqlite-net 上的代码示例匹配好吧。但考虑到类似的问题,显然代码示例是错误的:

Android table creation Failure (near "autoincrement": syntax error)?

通过删除自动增量解决了该问题。或者引用http://www.sqlite.org/faq.html#q1 :

Short answer: A column declared INTEGER PRIMARY KEY will autoincrement.

(创建表后,请仔细检查ID列实际上是否具有INTEGER PRIMARY KEY类型。)

Longer answer: If you declare a column of a table to be INTEGER PRIMARY KEY, then whenever you insert a NULL into that column of the table, the NULL is automatically converted into an integer which is one greater than the largest value of that column over all other rows in the table, or 1 if the table is empty.

确保您的 INSERT 语句不包含列 ID 的显式值(NULL 除外),否则该列将不会自动-增量。如果这在 SQLite-net 中不可能(您可能需要一个调试器),那么这很可能是一个错误。尽管令人惊讶的是没有其他人遇到过这种情况。

也许您需要使属性 ID 可为空(即使用类型 int?;是的,带有问号)。请注意,我只是在这里猜测;您可能需要尝试一下。