gpt4 book ai didi

c# - SQL Insert 命令抛出错误

转载 作者:行者123 更新时间:2023-11-30 14:47:27 24 4
gpt4 key购买 nike

 System.Data.SqlClient.SqlException occurred   HResult=0x80131904   Message=Cannot insert explicit value for identity column in table 'DriversDetailsTable' when IDENTITY_INSERT is set to OFF.   Source=.Net SqlClient Data Provider   StackTrace: <Cannot evaluate the exception stack trace>

当我运行我的代码时,我不断收到上述错误,不知道为什么。这是我的代码:

SqlConnection conn = new SqlConnection(@"Data Source = ComputerName\SQLEXPRESS;Initial Catalog = Drivers;Trusted_Connection=True;");
conn.Open();

SqlDataAdapter adapter = new SqlDataAdapter();

SqlCommand command = new SqlCommand($@"INSERT INTO DriversDetailsTable (name, Id, DateJoined) VALUES ('Driver4', 1, '2017-07-06')", conn);
command.ExecuteNonQuery();

conn.Close();

最佳答案

是的,那是因为您的 Id 列是 IDENTITY 列,因此您应该在 INSERT 语句中省略它,如下所示。因为它是一个 IDENTITY 列,所以你不能明确地为它插入值,除非你将 IDENTITY_INSERT 设置为 OFF,但你认为你不想这样做不管怎样

INSERT INTO DriversDetailsTable (name, DateJoined) VALUES ('Driver4', '2017-07-06')

旁注:当您使用硬编码/静态值时,看不到 C#6 字符串插值语法 $@"INSERT 的原因

关于c# - SQL Insert 命令抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44943367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com