-6

我创建了一个数据库,其中列有名字 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);
4

2 回答 2

2

由于您没有为 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);
    }
}
于 2012-06-20T03:25:37.297 回答
1

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

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

于 2012-06-20T02:34:14.550 回答