【问题标题】:Violation of PRIMARY KEY constraint in Sql Server [closed]违反 Sql Server 中的 PRIMARY KEY 约束[关闭]
【发布时间】:2012-06-20 02:29:13
【问题描述】:

我创建了一个数据库,其中包含名字 lastname 、Id 、到达日期和今天日期等列。都是 nchar() 的数据类型;我现在在网页中将 ID 作为主键,我输入了 vales 并单击了提交,但出现了一个错误

违反主键约束:无法在对象“dbo.Accomdation”中插入重复键。 声明已终止。

代码为

    SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=Accomdation;Integrated Security=True");
    con.Open();

    string f = TextBox1.Text;
    string g = TextBox5.Text;
    string d = DropDownList1.Text;
    string s = TextBox1.Text;
    string a = TextBox2.Text;
    string h = TextBox7.Text;
    string k = TextBox6.Text;
    string u = TextBox8.Text;
    string sql=("INSERT INTO Accomdation ([First Name], [LAst Name], Gender, [UHCL ID], [Date OF arrival], [FLight No], Email)VALUES        ('tya', 'tya', 'tya', 'tya', 'tya', 'tya', 'tya')");

    SqlCommand sw = new SqlCommand(sql,con);

【问题讨论】:

  • 请查看您的插入语句。
  • 首先,如果您的插入重复包含值tya,您应该能够看到问题。其次,你需要学会真正阅读错误信息的文字,你可以确切地看到这里的问题。
  • @KenWhite 你真的想让他花脑子而不是打扰别人?来吧——只要有很多程序员是他的水平,我就可以每天打电话给我。

标签: c# asp.net


【解决方案1】:

由于您没有为 ID 插入值,因此您应该将该 ID 设为自动递增而不是 null。

如下所示。

create table Accomdation(
   AccID int not null identity(1,1) primary key,

   define other columns 

 )

并通过 SqlCommand 使用参数化查询,这里是示例代码

string commandText = "INSERT INTO Accomdation ([First Name], [LAst Name]) VALUES (@FirstName, @LastName)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(commandText, connection);
    command.Parameters.AddWithValue("@FirstName", firstName);
    command.Parameters.AddWithValue("@LastName", lastName);

    try
    {
        connection.Open();
        command.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

【讨论】:

    【解决方案2】:

    ID(主键)是身份吗?它需要。主键是复合聚集索引/如何? 该错误表示您正在尝试将某些内容插入到已经存在的 PK 中。

    从表中选择并查看存在的内容。尝试在 Management Studio 中只运行插入语句,使用不同的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多