I\'ve come from Java experience and am trying to start with C#. I\'ve read SqlConnection SqlCommand SqlDataReader IDisposable and I can understand that the best practice to
As VMAtm has said, .net Pools the connections on it's own, so it is perfectly ok to recreate them. As such I generally write a wrapper for the whole process like this one.
public static void RunWithOpenSqlConnection(string connectionString, Action connectionCallBack)
{
SqlConnection conn = null;
try
{
conn = new SqlConnection(connectionString);
connectionCallBack(conn);
}
catch (Exception ex)
{
//Log Error Here
}
finally
{
if (conn != null)
conn.Dispose(); //will close the connection
}
}
public static void ExecuteSqlDataReader(string connectionString, string sqlCommand, Action readerCallBack)
{
RunWithOpenSqlConnection(connectionString, delegate(SqlConnection conn)
{
SqlCommand cmd = null;
SqlDataReader reader = null;
try
{
cmd = new SqlCommand(sqlCommand, conn);
reader = cmd.ExecuteReader();
readerCallBack(reader);
}
catch (Exception ex)
{
//Log Error Here
}
finally
{
if (reader != null)
reader.Dispose();
if (cmd != null)
cmd.Dispose();
}
});
}
//Example calling these
ExecuteSqlDataReader(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString, "Select EmployeeID FROM Employees;", delegate(SqlDataReader reader)
{
List employeeIds = new List();
if (reader.HasRows)
{
while(reader.Read())
{
employeeIds.Add((string)reader[0]);
}
}
});