C# 如何防止添加重复条目?
我应该在代码中添加什么?我应该避免在代码中添加重复的条目。提前谢谢C# 如何防止添加重复条目?,c#,duplicates,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.Par
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");
可以使用ExecuteScalar()从任何查询的第一行和第一列返回值。执行select计数并检查它是否返回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)";
解决方案一:在字段(列)类别上添加一个约束,或者在数据库中调用任何字段,并捕获数据库中已经存在的异常 解决方案二:在查询中检查值是否已经存在 这两种解决方案都可以引发异常,也可以使用
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 ...
}
请记住,当您在字段
类别
上放置约束时,如果(affectedRows==1)将唯一约束添加到列并吞并该异常,或者将如果不退出
逻辑添加到插入SQL,则会在之前抛出异常。取决于您使用的数据库-添加一个标记来标识它。请注意,有人可能会在您的两个查询之间插入一个值。我会使用唯一的约束来确保数据的完整性。谢谢。我认为将其设置为主键可以解决这个问题。计数(*)对于检查值来说是非常有害的,因为需要两次到db并忽略原子性。当然,如果它是主键,db将确保唯一性。