Rule Definition
It is highly recommended to tie the lifetime of the connection to the SqlDataReader object, by passing the CommandBehavior.CloseConnection enumerated value to the ExecuteReader method.
What the CommandBehavior.CloseConnection does is close the underlying connection whenever the reader is closed. It is quite easy to forget to close database connections, and thereby waste resources that may be quite scarce, leading to serious application availability and stability issues.
Remediation
Use theCommandBehavior.CloseConnection call style when calling the ExecuteReader method.
Violation Code Sample
String strConn =
ConfigurationSettings.AppSettings["myConnection"].ToString();
SqlConnection sqlConn = new SqlConnection(strConn);
SqlCommand sqlComm = new SqlCommand("p_my_procedure", sqlConn);
sqlComm.CommandType = CommandType.StoredProcedure;
sqlComm.Parameters.Add(new SqlParameter("@bitSomeResult", SqlDbType.Bit));
sqlComm.Parameters["@bitSomeResult"].Direction = ParameterDirection.Output;
sqlConn.Open();
SqlDataReader dr = sqlComm.ExecuteReader();
String strSomeResult =
sqlComm.Parameters["@bitSomeResult"].Value.ToString();
if (strSomeResult.ToLower() == "True".ToLower())
{
//Do something
}
else
{
//Do something else
}
sqlConn.Close();
Fixed Code Sample
SqlDataReader reader;
SqlCommand cmd = new SqlCommand("SELECT Facility FROM Tbl_Facilities", cn);
try
{
if(cn.State != ConnectionState.Open){cn.Open();}
}
catch(SqlException ex)
{
Debug.Assert(false, ex.ToString);
}
try
{
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch(System.Exception ex)
{
Debug.Assert(false, ex.ToString());
}
while(reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
reader.Close;
Console.WriteLine(cn.State);//Closed
}
Reference
.NET Data Access Architecture Guide
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/daag.asp
Know Dot Net - IDataReader and the CommandBehavior Enumeration
http://www.knowdotnet.com/articles/schemas2.html
Related Technologies
.Net
Technical Criterion
Efficiency - Memory, Network and Disk Space Management
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.