如何清除System.Data.SqlClient.SqlException错误?

时间:2016-08-02 11:16:10

标签: asp.net

当我执行更新操作时,错误

  

“System.Data.dll中发生'System.Data.SqlClient.SqlException'类型的异常,但未在用户代码中处理”

发生了,如何删除?cmd.ExecuteNonQuery(插入查询下面的行)出现此错误

protected void Button2_Click(object sender, EventArgs e)
{
        SqlConnection con = new SqlConnection() ;
        con.ConnectionString = @"Data Source=ADMIN\LOCALHOST;Initial Catalog=maha;Integrated Security=True;";

                con.Open();

                SqlCommand cmd = new SqlCommand("Insert into [dbo].[student]([ID],[NAME],[DOB],[GENDER]) Values ('" + TB1.Text + "','" + TB2.Text + "','" + TB3.Text + "','" + @rm + "')", con);

                cmd.ExecuteNonQuery();
                con.Close();
}
protected void Button3_Click(object sender, EventArgs e)
{
        SqlConnection con = new SqlConnection();
        con.ConnectionString = @"Data Source=ADMIN\LOCALHOST;Initial Catalog=maha;Integrated Security=True;";
        con.Open();

        SqlCommand cmd = new SqlCommand("Update [dbo].[student] set [ID]='" + TB1.Text + "',[NAME]='" + TB2.Text + "',[DOB]='" + TB3.Text + "',[GENDER]='" + @rm + "' where [ID]=='" + TB1.Text + "'", con);
        cmd.ExecuteNonQuery();
        con.Close();
 }

1 个答案:

答案 0 :(得分:0)

您的代码中有一些错误,您可以使用Exception捕获try{} catch{}。此外,我建议您使用using语句。

错误

Insert两个SqlParameter查询中,您使用的是@rException并且您没有为它提供价值。所以它显然会抛出==Update查询中的protected void Button3_Click(object sender, EventArgs e){ try{ string constr = @"Data Source=ADMIN\LOCALHOST;Initial Catalog=maha;"+ "Integrated Security=True;"; using(SqlConnection con = new SqlConnection(constr)){ if(con.State==ConnectionState.Closed){ con.Open(); } string query= "Update [dbo].[student] set [ID]=@id,[NAME]=@name, [DOB]=@dob,"+ "[GENDER]=@rm Where [ID]=@id"; using(SqlCommand cmd = new SqlCommand(query, con)){ cmd.CommandType=CommandType.Text; cmd.Parameters.AddWithValue("@id",TB1.Text); cmd.Parameters.AddWithValue("@name",TB2.Text); cmd.Parameters.AddWithValue("@dob",TB3.Text); cmd.Parameters.AddWithValue("@rm",rmvalue); //i don't know it's value cmd.ExecuteNonQuery(); //success message here } } }catch(Exception ex){ //print your error message here e.g errLabel.Text=ex.Message; } 也是错误,它在SqlServer中不存在。

现在试试这段代码:

Insert

}

我建议您对Update.menuOptionSelectedWrap { float: left; width: 33%; height: 100%; margin: auto; margin-right: -4px; background-color: #d6eef2; display: table; } .menuOptionSelectedWrap:last-of-type { width: 34%; }

使用此方法