When using SqlDataReader to operate the database during coding, do you manually call the method or write code to close the database connection every time after calling your database method? (Haha, I used to do this for fun)
The following method can solve this problem. The parameter CommandBehavior.CloseConnection of cmd.ExecuteReader will automatically help you close the associated conn
public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
try
{
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
// Adding the parameter CommandBehavior.CloseConnection to cmd.ExecuteReader will automatically close the conn associated with it after cmd.ExecuteReader is executed.
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch
{
conn.Close();
throw;
}
}
http://www.cnblogs.com/abeen/archive/2006/12/19/597039.html