Here’s my code for a SQL connection. Not sure if I have handled all errors. Instead of Using should I just use Try Catch block?
using (SqlConnection con = new SqlConnection(GetSQLConnectionString()))
{
string cmdStr = "INSERT INTO table1.....";
using (SqlCommand cmd = new SqlCommand(cmdStr, con))
{
//Store parameters with values to the collection
cmd.Parameters.AddWithValue("NAME", NAME);
cmd.Parameters.AddWithValue("ID",ID);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
lblError.Text = ex.ToString();
}
if (con != null)
con.Close();
}
}
I’d re-write your current catch block to only catch
SQLException– catching anyExceptionis rarely correct. This would also mean that you could produce prettier output (formatting each separate SQLError object), include a total error count, or react to specific errors that you know your code can handle.A general rule for exception handling is to only catch exceptions that your code can correctly deal with at that point (hence the general avoidance of catching
Exception). You’d generally install a single top level “unhandled Exception” handler in your app that will log other exceptions and shut down the app. If you don’t know what the exception is, how can you hold a belief that your code can continue to operate successfully when it has occurred?As Neil says, you don’t need to explicitly close the connection since the
usingblock guarantees this as well.