Whats the best way to consume sql resources and ensure they are released when finished? I previously used alot of "finally" statements, however that doesnt always seem to release properly, especially if im returning a value (within the try block, ya i know). And lately i see alot of code examples that dont even use the finally block.
I'll post a few of "my way", if you could help identify a best practice change for me, that would be super!
How would i change at least the ExecuteNonQuery sample to use the using() mechanism? If that is the better way to go.
1. ExecuteNonQuery's
2. DataSet's
I'll post a few of "my way", if you could help identify a best practice change for me, that would be super!
How would i change at least the ExecuteNonQuery sample to use the using() mechanism? If that is the better way to go.
1. ExecuteNonQuery's
Code:
public void updatePackageShip(int formID, string notes)
{
SqlConnection sqlCon = new SqlConnection(conString);
SqlCommand sqlCom = new SqlCommand("config_UpdatePackageShip", sqlCon);
sqlCom.CommandType = CommandType.StoredProcedure;
sqlCom.Parameters.Add("@fid", SqlDbType.Int).Value = formID;
sqlCom.Parameters.Add("@notes", SqlDbType.VarChar, 2000).Value = notes;
try
{
sqlCon.Open();
sqlCom.ExecuteNonQuery();
sqlCon.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
2. DataSet's
Code:
public DataSet ToDoList(int userID)
{
SqlConnection sqlCon = new SqlConnection(conString);
SqlCommand sqlCom = new SqlCommand("sp_OppToDo", sqlCon);
sqlCom.CommandType = CommandType.StoredProcedure;
sqlCom.Parameters.Add("@userID", SqlDbType.Int).Value = userID;
SqlDataAdapter da = new SqlDataAdapter(sqlCom);
DataSet ds = new DataSet();
try
{
da.Fill(ds);
sqlCon.Close();
return ds;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}