如何防止添加重复条目?

时间:2015-10-29 17:07:15

标签: c# duplicates

我应该在此代码中添加什么?我应该避免在我的代码中添加重复的条目。提前致谢

protected void btnAdd_Click(object sender, EventArgs e)
{
    con.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandText = "INSERT INTO Categories VALUES(@Category)";
    cmd.Parameters.AddWithValue("@Category", txtName.Text);
    cmd.ExecuteNonQuery();
    con.Close();
    Response.Redirect("/Admin/Categories/Add.aspx");

2 个答案:

答案 0 :(得分:0)

您可以使用ExecuteScalar()从任何查询的第1行和第1列返回值。做一个选择计数并检查它是否返回1.

using (SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(*) from Categories where Category = @1", con))
{
    con.Open();
    sqlCommand.Parameters.AddWithValue("@1", txtName.Text);
    int userCount = (int) sqlCommand.ExecuteScalar();
    if(userCount == 1)
    {
        //already exists
    }
    else
    {
        //proceed
    }
}

同样在设计数据库时,最好将其作为主键。

根据@Alex的建议,使用以下查询代替您拥有的内容

cmd.CommandText = "IF NOT EXISTS(SELECT * FROM Categories WHERE CATEGORY=@1) INSERT INTO Categories VALUES(@1)";

答案 1 :(得分:0)

解决方案一:在字段(列)类别上添加约束 - 或者在数据库中调用任何字段,并在数据库中已存在时捕获异常。

解决方案二:在查询中检查该值是否已存在。

两个解决方案都可以抛出异常,或者可以使用[Login] Reading... [Login] Reading... [Login] Loaded username.acc succesfully. username password false 的返回值,这是受影响的行数,同样:

SqlCommand.ExecuteNonQuery()

请记住,当您在字段protected void btnAdd_Click(object sender, EventArgs e) { con.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandText = "IF NOT EXISTS(SELECT Category FROM Categories WHERE Category=@Category) INSERT INTO Categories VALUES(@Category)"; cmd.Parameters.AddWithValue("@Category", txtName.Text); int affectedRows = cmd.ExecuteNonQuery(); con.Close(); if (affectedRows == 1) //1 record was updated, thus we can conclude that the record was successfully inserted { Response.Redirect("/Admin/Categories/Add.aspx"); //Perform other logic ... } 上放置约束时,它会在Category之前抛出异常。