C# 如何在违反唯一密钥时获取警报

C# 如何在违反唯一密钥时获取警报,c#,alert,unique-key,C#,Alert,Unique Key,如果数据库检测到唯一密钥冲突,则此行 protected void Button1_Click(object sender, EventArgs e) { SqlConnection myConnection = new SqlConnection("server=VIVID-PC;Integrated Security = True;Database=SchoolDb"); SqlCommand myCommand = new SqlCommand("

如果数据库检测到唯一密钥冲突,则此行

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");

    }
将引发异常。您可以捕获该异常并继续使用自己的代码:

myCommand.ExecuteNonQuery();
请注意,您的代码容易受到SQL注入攻击。您应该使用命令参数,而不是手动构建SQL。此外,您应该使用
使用
块()

如果无法将行插入数据库,则会引发异常。在你的情况下,这很可能是一个错误。抓住它。

使用您的(阅读备注部分)来检测插入失败。您可以使用异常或受影响零件的行数

试试这个:

try
{
    myCommand.ExecuteNonQuery();
}
catch(Exception e)
{
    // right here, "something" went wrong. Examine e to check what it was.
}
试试看
{
…剩下的代码
...
int rowsAffected=myCommand.ExecuteNonQuery();//最有可能的情况是,在唯一密钥冲突的情况下,它将引发异常。否则,仍然没有行受到影响

如果(rowsAffected如注释中所示,请使用命令参数

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
}
您还可以在catch块中循环不同的sql错误

  • 确保您处理了连接和命令()
  • 不要创建虚拟命令对象
  • 以下是完整的代码:

    try
    {
       //Your other code 
      _myCommand.ExecuteNonQuery();
       myConnection.Close();
       Response.Redirect("/view.aspx");
    }
    catch(SqlException sqlExc)
    {
     // Your popup or msg.
    }
    

    进一步考虑-改进代码中的命名-TextBox1、TextBox2等对读者来说没有任何意义。给他们适当的名称,如StudentNameTextBox、RollNoTextBox等。另外,最好的做法是拆分数据访问和UI逻辑。

    检测到。使用命令参数,我找不到你。具体帮助我,我是初学者。你可以单击linkthnks为suggestionanytime好友,快乐编码
    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
        }
    }