SQLDataReader and CommandBehaviour.CloseConnection

本文关键字:CloseConnection CommandBehaviour and SQLDataReader | 更新日期: 2023-09-27 18:05:29

我有一个名为"db"的通用类,它直接与数据库对话。并有一个名为"ExecuteDataReader"的方法,如下所示:

public SqlDataReader ExecuteDataReader(SqlCommand cmd)
        {
            try
            {
                OpenConnection();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.StoredProcedure;              
                SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return dr;
            }
            catch (Exception ex)
            {
                Utils.Debug(string.Format("Err in {0}.{1} : {2}'nSQL : {3}", this.GetType(), "ExecuteDataReader", ex.Message, cmd.CommandText));
                return null;
            }            
        }

然后,我执行资源密集型查询,循环遍历数据库中的10000条父记录和20000条子记录以更新。然后我得到了以下错误:

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

为了解决这些问题,我必须在执行后显式调用dr.Close()。

static void ProcessAssessmentCriteria(string UnitReference)
        {
            SqlCommand cmd = new SqlCommand("TRACKING.DBTool_GetUniqueAssessmentCriteriaByUnitReference");
            cmd.Parameters.Add("@UnitReference", SqlDbType.VarChar, 20).Value = UnitReference;
            SqlDataReader dr = db.ExecuteDataReader(cmd);
            if (dr.HasRows)
            {
                while (dr.Read())
                {                    
                    ProcessDetailAssessmentCriteria(UnitReference, dr["AssessmentRefNumber"].ToString());
                    Console.WriteLine("---------------");
                }
            }
            dr.Close();
        }

据我所知,CommandBehaviour.CloseConnection()会自动关闭连接。但现在似乎还没有关闭。你能给我点化一下吗?谢谢。

SQLDataReader and CommandBehaviour.CloseConnection

CommandBehavior。从MSDN关闭连接

命令执行时,关联的Connection对象为

所以只有当你关闭DataReader的连接是关闭的