如何在违反唯一键时收到警报
本文关键字:一键 唯一 | 更新日期: 2023-09-27 18:35:08
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("server=VIVID-PC;Integrated Security = True;Database=SchoolDb");
SqlCommand myCommand = new SqlCommand("Command String", myConnection);
myConnection.Open();
string firstText = TextBox1.Text;
string SecondText = TextBox2.Text;
string thirdText = TextBox3.Text;
string fourthText = TextBox4.Text;
myCommand = new SqlCommand("INSERT INTO SchoolDb_Student(StudentName,RollNo,Session,MobileNo)values('" + firstText + "','" + SecondText + "' , '" + thirdText + "','" + fourthText + "')", myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Redirect("/view.aspx");
}
- 使用带参数的命令将数据传递到服务器。
- 确保释放连接和命令(通过 using 语句)
- 将连接字符串存储在配置文件中
- 不创建虚拟命令对象
这是完整的代码:
using(var connection = new SqlConnection(connectionString))
using(var command = connection.CreateCommand())
{
command.CommandText =
@"INSERT INTO SchoolDb_Student(StudentName,RollNo,Session,MobileNo)
VALUES (@studentName, @rollNo, @session, @mobileNo)";
command.Parameters.AddWithValue("studentName", TextBox1.Text);
command.Parameters.AddWithValue("rollNo", TextBox2.Text);
command.Parameters.AddWithValue("session", TextBox3.Text);
command.Parameters.AddWithValue("mobileNo", TextBox4.Text);
connection.Open();
try
{
command.ExecuteNonQuery();
}
catch(SqlException e)
{
if (e.Message.Contains("Violation of UNIQUE KEY constraint"))
// you got unique key violation
}
}
进一步的注意事项 - 改进代码中的命名 - TextBox1,TextBox2等对读者没有任何意义。给他们适当的名称,如StudentNameTextBox,RollNoTextBox等。另一个好的做法是拆分数据访问和 UI 逻辑。
如果数据库检测到唯一键冲突,则此行
myCommand.ExecuteNonQuery();
将引发异常。您可以捕获该异常并继续使用自己的代码:
try
{
myCommand.ExecuteNonQuery();
}
catch(Exception e)
{
// right here, "something" went wrong. Examine e to check what it was.
}
请注意,您的代码容易受到 SQL 注入攻击。您应该使用命令参数,而不是手动构建 SQL。此外,您应该使用using
块(有关详细信息,请参阅此处)
如果无法将行插入数据库,则执行非查询将引发异常。在您的情况下,它很可能是 SqlException。抓住它。
使用 ExecuteNonQuery() 中的 returnType(阅读备注部分)来检测插入失败。 您可以使用例外或编号。 受影响的部分行数
试试这个:
try
{
... your rest of the code
...
int rowsAffected = myCommand.ExecuteNonQuery(); // Most probaboly it will throw exception in case of Unique key violation. If not, still no rows have been affected
if(rowsAffected<1)
{
//your Alert for no records inserted
}
else
{
//your alert for successful insertion
}
}
catch(SqlException ex)
{
//check the exception and display alert
}
finally
{
//release connection and dispose command object
}
如注释中建议的那样,使用命令参数。
try
{
//Your other code
_myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Redirect("/view.aspx");
}
catch(SqlException sqlExc)
{
// Your popup or msg.
}
您还可以在 catch 块中循环不同的 sql 错误。