[英]How to insert data into sql server database when the primary key column already set default identity(1, 1)
I'm trying to insert two data columns into my SQL Server database but I get an error at the code line -> cmd.ExecuteNonQuery();
我正在尝试将两个数据列插入到我的 SQL Server 数据库中,但在代码行中出现错误 ->
cmd.ExecuteNonQuery();
Cannot insert the value NULL into column
OrderID
, tableRestaurantApp.dbo.Junc_Order
;无法将值 NULL 插入到
OrderID
列、表RestaurantApp.dbo.Junc_Order
; column does not allow nulls.列不允许空值。 INSERT fails.
插入失败。
The OrderID
column is actually the primary key in my data table. OrderID
列实际上是我的数据表中的主键。 I set it identity(1, 1) and want to insert other data and meanwhile it can insert 1, 2, 3, 4....automatically.我将它设置为 identity(1, 1) 并想插入其他数据,同时它可以插入 1, 2, 3, 4 ..... 自动。
Here is the part of my code:这是我的代码的一部分:
string insertString = "INSERT INTO Junc_Order(ID, Quantity)values (@ID, @Quantity)";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.Parameters.AddWithValue("@ID", r_ID);
cmd.Parameters.AddWithValue("@Quantity", r_Quantity);
cmd.ExecuteNonQuery();
I already get connection with database ahead of these codes, so the problem should not be that.我已经在这些代码之前与数据库建立了连接,所以问题不应该是那个。
Updated Junc_Order table design:更新 Junc_Order 表设计:
OrderID (PK,FK,int,not null)
ID(FK,int,not null)
Quantity(int,not null)
By viewing your question, it seems that your insert query is not correct:通过查看您的问题,您的插入查询似乎不正确:
second, somewhere you are getting "r_ID" as null that's why you are facing error.Verify it and modify your code with the following:其次,在某处您将“r_ID”设为空,这就是您面临错误的原因。验证它并使用以下内容修改您的代码:
string insertString = "INSERT INTO Junc_Order(Quantity) values(@Quantity)"; string insertString = "INSERT INTO Junc_Order(Quantity) values(@Quantity)"; SqlCommand cmd = new SqlCommand(insertString, conn);
SqlCommand cmd = new SqlCommand(insertString, conn); cmd.Parameters.AddWithValue("@Quantity", r_Quantity);
cmd.Parameters.AddWithValue("@Quantity", r_Quantity); cmd.ExecuteNonQuery();
cmd.ExecuteNonQuery();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.