将数据插入SQL后显示消息未显示

时间:2020-01-15 13:41:53

标签: c# asp.net sql-server

将数据插入数据库后,我试图显示一条成功消息,但未显示。

这是我的代码:

 protected void BtnSubmit_Click(object sender, EventArgs e)
{
    string ProjectName = txtProjectName.Text;
    string ProjectCode = txtProjectCode.Text;
    string ProjectDetails = txtProjectDetails.Text;

    try
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["PROJECTS"].ConnectionString);
        SqlCommand cmd = new SqlCommand("INSERT INTO tbl_projects (projectName, projectCode, projectDetails) VALUES (@ProjectName, @ProjectCode, @ProjectDetails)");

        cmd.Connection = con;
        con.Open();

        cmd.Parameters.AddWithValue("@ProjectName", txtProjectName.Text);
        cmd.Parameters.AddWithValue("@ProjectCode", txtProjectCode.Text);
        cmd.Parameters.AddWithValue("@ProjectDetails", txtProjectDetails.Text);

        cmd.ExecuteNonQuery();
        con.Close();
    }
    catch (SqlException ex)
    {
        Toastr.ShowToast(ex.Message, "Success", Toastr.Type.Success);
    }

}

如果还尝试过:

 catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Success", Toastr.Type.Success);
    }

不确定为什么这不起作用吗?

2 个答案:

答案 0 :(得分:2)

遇到异常时,您尝试发出成功消息。

基本上,异常是由您的代码引起的错误。因此,相反,您应该将成功消息放在插入之后,并且如果未引发任何异常,则表示成功。

SqlConnection con = null;   //Put this outside your try block
try
{
    con = new SqlConnection(ConfigurationManager.ConnectionStrings["PROJECTS"].ConnectionString);
    SqlCommand cmd = new SqlCommand("INSERT INTO tbl_projects (projectName, projectCode, projectDetails) VALUES (@ProjectName, @ProjectCode, @ProjectDetails)");

    cmd.Connection = con;
    con.Open();

    cmd.Parameters.AddWithValue("@ProjectName", txtProjectName.Text);
    cmd.Parameters.AddWithValue("@ProjectCode", txtProjectCode.Text);
    cmd.Parameters.AddWithValue("@ProjectDetails", txtProjectDetails.Text);

    cmd.ExecuteNonQuery();
    Toastr.ShowToast(ex.Message, "Success", Toastr.Type.Success);

}
catch (SqlException ex)
{
    Toastr.ShowToast(ex.Message, "Error:  Oh no, it didn't work!", Toastr.Type.Failed);
}
finally
{
    //Close you connection (if set) in finally.  
    //This way it will also be closed if you do have an exception
    if(con != null)
        con.Close();
}

此外,在您当前的代码中,仅当您的命令成功执行时,才会关闭与数据库的连接。这意味着如果有异常,则连接保持打开状态,并且存在内存泄漏和资源问题。

所以我将其移到了finally块中,无论是否发生异常,该块也将被执行。但是然后您需要在尝试关闭之前检查它是否已填充

答案 1 :(得分:1)

Try {
// All statements here are executed until exception is reached, if all statements pass then one can display a success message. Thus at the end of the try statement(s) add the success message there.
} 
Catch (Exception ex) {
// When Something goes wrong with the statements in Try then the exception message will be thrown.  
}
// I would rather suggest that a success message be thrown at the end of your try statement...```