2016-08-02 100 views
0

当我执行更新操作,则错误如何清除System.Data.SqlClient.SqlException错误?

“类型‘System.Data.SqlClient.SqlException’出现在system.data.dll但在用户代码中没有处理的异常”

发生,我怎么能删除吗?这个错误是在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(); 
} 
+2

你的代码是开放的SQL注入攻击。我建议你开始使用[SqlParameter](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter(v = vs.110).aspx) – Satpal

+0

这个异常可能表明您正在创建的SQL中存在一些错误。创建命令后,cmd的'CommandText'是什么? – bassfader

+0

不完全重复,但请查看http://stackoverflow.com/q/35163361/87698。作为一个副作用,它也可能解决你原来的问题。关于您的原始问题:您的异常还有*异常消息*。找到它并将其添加到您的问题。 – Heinzi

回答

0

那么你必须在你的代码中的一些错误和发生,你可以赶上Exception用u唱歌try{} catch{}。此外,我会建议使用using声明。

错误

在这两个Insert查询您使用的是SqlParameter@r,你是不是为它提供价值。所以很明显会抛出并且Exception, ==Update查询也是一个错误,它不存在于SqlServer中。

现在试试这个代码:

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][email protected],[NAME][email protected], [DOB][email protected],"+ 
         "[GENDER][email protected] Where [ID][email protected]"; 
      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; 
    } 

}

我建议你使用这种方法,两个InsertUpdate

+0

我试过这段代码,但它没有执行查询。总是发现catch块。如何解决这个问题? –

+0

什么是异常消息说? – jonju

+0

我在catch块打印的消息,我该如何解决?我想在没有任何异常的情况下执行查询 –

相关问题