如何在违反唯一键时获取警报

时间:2014-12-23 10:40:40

标签: 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("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");

    }

5 个答案:

答案 0 :(得分:1)

  1. Use command with parameters to pass data to server
  2. 确保您处置连接和命令(via using statement
  3. Store connection strings in config file
  4. 不要创建虚拟命令对象
  5. 这是完整的代码:

    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逻辑。

答案 1 :(得分:0)

如果数据库检测到唯一的密钥违规,则此行

myCommand.ExecuteNonQuery();

会抛出异常。您可以捕获该异常并继续使用您自己的代码:

try
{
    myCommand.ExecuteNonQuery();
}
catch(Exception e)
{
    // right here, "something" went wrong. Examine e to check what it was.
}

请注意,您的代码容易受到SQL注入攻击。您应该使用命令参数而不是手动构建SQL。此外,您应该使用using块(see here for details

答案 2 :(得分:0)

如果

ExecuteNonQuery无法将行插入数据库,则会抛出异常。在您的情况下,它很可能是SqlException。抓住它。

答案 3 :(得分:0)

使用您的returnType from ExecuteNonQuery()(阅读备注部分)来检测插入失败。你可以使用例外或否。行影响部分

试试这个:

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
}

答案 4 :(得分:0)

正如评论中所建议的那样使用命令param。

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

你还在catch块中循环不同的sql错误。