[英]How do I append a new id to record
I have a problem, basically I want the id in database to autoincrement and add more users, however when i try to add a 2nd record, it drops an error such as:我有一个问题,基本上我希望数据库中的 id 自动递增并添加更多用户,但是当我尝试添加第二条记录时,它会抛出一个错误,例如:
constraint failed
Unique constraint failed: DANE.id
this is my inserting method:这是我的插入方法:
private void LoadToDb_Click(object sender, EventArgs e)
{
var modelData = new Data();
var db = new SqlDb();
var sqLiteConnection = db.Connect();
var sqLiteCommand = sqLiteConnection.CreateCommand();
try
{
modelData.Name = firstName.Text;
modelData.Age = Convert.ToInt32(DisplayAge.Text);
modelData.LastName = LastName.Text;
sqLiteCommand.CommandText =
$"insert into DANE values('{modelData.Name}', '{modelData.LastName}', '{modelData.Age}', {Interlocked.Increment(ref modelData.Id)})";
sqLiteCommand.ExecuteNonQuery();
db.Disconnect();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
This is my Data Model这是我的数据模型
public class Data
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public int id = 0;
}
and this is sqLite database pattern (I use db browser for that)这是 sqLite 数据库模式(我为此使用 db 浏览器)
CREATE TABLE "DANE" (
"FirstName" TEXT NOT NULL,
"LastName" TEXT NOT NULL,
"Age" INTEGER NOT NULL,
"id" INTEGER NOT NULL,
PRIMARY KEY("id" AUTOINCREMENT)
);
You are using Data.Id as primary key, but you create a new instance every time.您使用 Data.Id 作为主键,但每次都创建一个新实例。 So your primary key will always be 1 (0 as soon as you create the new instance, then 1 when you call Interlocked.Increment on it, which btw is probably not needed).
因此,您的主键将始终为 1(创建新实例后立即为 0,然后在调用 Interlocked.Increment 时为 1,顺便说一句,可能不需要)。
Also you are generating the primary key both in your code and in the database.此外,您正在代码和数据库中生成主键。 Choose the one you prefer, no need to do it twince.
选择您喜欢的一种,无需特意去做。
your table defined with "id" INTEGER NOT NULL, PRIMARY KEY("id" AUTOINCREMENT)
您的表定义为
"id" INTEGER NOT NULL, PRIMARY KEY("id" AUTOINCREMENT)
So, your insert needs to be like所以,你的插入需要像
$"insert into DANE (FirstName, LastName, Age)
values('{modelData.Name}', '{modelData.LastName}', '{modelData.Age}')";
Basically, you don't list auto increment column in INSERT
.基本上,您不会在
INSERT
列出自动增量列。 But you need to retrieve inserted record value based on SqlLite-specific DB syntax and provider capabilities.但是您需要根据 SqlLite 特定的数据库语法和提供程序功能检索插入的记录值。 Each DB engine and its .NET provider has its own way of doing it.
每个数据库引擎及其 .NET 提供程序都有自己的方法。
TIP: SQLiteConnection.LastInsertRowId
提示:
SQLiteConnection.LastInsertRowId
DEFINE TABLE LIKE THIS:像这样定义表格:
CREATE TABLE "DANE" (`enter code here`
"id" INTEGER NOT NULL AUTO_INCREMENT,
"FirstName" TEXT NOT NULL,
"LastName" TEXT NOT NULL,
"Age" INTEGER NOT NULL,
);
OR或者
var NewID = DB.DANE.Max(x => x.id) + 1;
and than add NewID as id in your insert query.然后在插入查询中添加 NewID 作为 id。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.