编码过程中使用SqlDataReader 来操作数据库时,你是否每次在调用完你的数据库方法后,再手动调用方法或写代码关闭数据库联接呢?(呵呵 我以前是这样做的 见笑)
下面的方法可以完成解决此问题了,cmd.ExecuteReader的参数CommandBehavior.CloseConnection会自动帮你关闭与之相关联的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);

// 给cmd.ExecuteReader加上参数CommandBehavior.CloseConnection会在cmd.ExecuteReader执行完后自动关闭与之相关联的conn
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

cmd.Parameters.Clear();

return rdr;

}

catch

{

conn.Close();

throw;

}

}
