简体   繁体   English

SQLite:插入到身份列

[英]SQLite: Insert Into Identity Column

I'm new to SQLite and I'm trying to run the following code: 我是SQLite的新手,正在尝试运行以下代码:

using (var cn = new SQLiteConnection("Data Source=:memory:;Version=3;")) {
    cn.Open();

    var cmd = cn.CreateCommand();
    cmd.CommandText = "CREATE TABLE [ContentItems] ([Id] [int] IDENTITY(1,1) NOT NULL, [Title] [nvarchar](100) NOT NULL, CONSTRAINT [PK_ContentItems] PRIMARY KEY ([Id]))";
    cmd.ExecuteNonQuery();

    var cmd2 = cn.CreateCommand();
    cmd2.CommandText = "INSERT INTO [ContentItems] (Title) VALUES ('Test 1')";
    cmd2.ExecuteNonQuery();
}

But this gives the error: 但这给出了错误:

Abort due to constraint violation ContentItems.Id may not be NULL 由于违反约束而中止ContentItems.Id不能为NULL

I've had a look through the documentation but based on my past SQL experience i cannot see why this doesn't work. 我浏览了文档,但是根据我过去的SQL经验,我看不出为什么这行不通。 I'd appreciate the help. 非常感谢您的帮助。 Thanks 谢谢

SQLite creates what you're thinking of as an IDENTITY column using the AUTOINCREMENT keyword. SQLite使用AUTOINCREMENT关键字创建您想作为IDENTITY列的内容。 In your example, the ID column is not created with AUTOINCREMENT and, since it is declared NOT NULL, you must supply a value. 在您的示例中,没有使用AUTOINCREMENT创建ID列,并且由于将其声明为NOT NULL,因此必须提供一个值。

The CREATE statement you're after is: 您要执行的CREATE语句是:

 CREATE TABLE [ContentItems] (
    [Id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 
    [Title] TEXT NOT NULL, 
    CONSTRAINT [PK_ContentItems] PRIMARY KEY ([Id])
 )

Note that SQLite uses the TEXT data type (although it will map anything containing "CHAR" to that datatype) and doesn't need or respect maximum field lengths. 请注意,SQLite使用TEXT数据类型(尽管它将将包含“ CHAR”的任何内容映射到该数据类型),并且不需要或不考虑最大字段长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM