【问题标题】:SQL Error when adding primary key添加主键时出现 SQL 错误
【发布时间】:2018-03-14 18:12:18
【问题描述】:

当我尝试添加新记录并因此添加主键时,出现错误:

发生 System.Data.SqlClient.SqlException
HResult=0x80131904
消息=违反主键约束“PK__Stock__BEAEB27A2652D17F”。无法在对象“dbo.Stock”中插入重复键。重复键值为 (39)。

我确定当前的记录总数为 38。主键是从一个数组中添加的,该数组的数字都在 39-44 之间。

我已附上以下代码:

int y = 0;

SqlCommand orderCommand3 = new SqlCommand();

string conString3 = Properties.Settings.Default.DatabaseEventsUnlimitedConnectionString;

using (SqlConnection connection3 = new SqlConnection(conString3))
{
    connection3.Open();

    while (ArrayCourseName[y] != "" && y <=5)
    {
        SqlCommand commandEvent = new SqlCommand("INSERT INTO STOCK (IngredientID, IngredientName, StorageType, QuantityInStock, MinimumRequired) VALUES (@p1, @p2, @p3, @p4, @p5)", connection3);

        commandEvent.Parameters.AddWithValue("@p1", ArrayIngredientID[y]);
        commandEvent.Parameters.AddWithValue("@p2", ArrayCourseName[y]);
        commandEvent.Parameters.AddWithValue("@p3", ArrayStorage[y]);
        commandEvent.Parameters.AddWithValue("@p4", ArrayQuantity[y]);
        commandEvent.Parameters.AddWithValue("@p5", ArrayMinimum[y]);

        int m = commandEvent.ExecuteNonQuery();

        if (m != 1)
        {
            throw new Exception("Too many records changed");
        }

        i++;
    }

    connection3.Close();
}

【问题讨论】:

  • 尝试使主键自动递增,您不必再担心添加它们或重复键,因为下一个数字将自动使用
  • 你正在使用 y 并在做 i++,这是如何工作的,或者它的错字....我认为应该是 y++
  • @PranayRana 做到了。您没有增加正确的变量,因此您第二次在数组中添加相同的记录,必然导致索引违规 - 并且恰好在您观察的值会导致错误的位置。伟大的收获,pranay!

标签: c# arrays sql-server executenonquery


【解决方案1】:

在您的代码中,您需要增加y 而不是i 的值,因为您使用y 作为索引值。

我建议你使用for循环会降低你代码的复杂度

for(int i=0;i<=5;i++) {
 if(string.IsNullOrWhiteSpace(ArrayCourseName[i] ))
   break;
 ///rest of the code
 using (SqlConnection connection3 = new SqlConnection(conString3))
 {
    connection3.Open();
    // code for sql non execute 
 }
}

我建议你每次都使用using 连接并创建连接对象,因为连接池每次都会处理池连接对象。

参考:Is it better to execute many sql commands with one connection, or reconnect every time?

【讨论】:

  • 当然要等几分钟!
  • @Bleari - 我知道我不好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-16
  • 2014-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多