如何防止添加重复条目
本文关键字:何防止 添加 | 更新日期: 2023-09-27 18:19:45
我应该在这个代码中添加什么?我应该避免在代码中添加重复条目。提前感谢
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()返回任何查询的第一行和第一列的值。进行选择计数并检查是否返回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)";
解决方案一:在字段(列)Category或数据库中调用的任何字段上添加约束,并在数据库中已经存在异常时捕获异常。
解决方案二:在查询中检查该值是否已经存在。
两种解决方案都可以抛出异常,或者可以使用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
上放置约束时,它将在if (affectedRows == 1)
之前抛出Exception。