gpt4 book ai didi

c# - SQLDataReader 和 CommandBehaviour.CloseConnection

转载 作者:行者123 更新时间:2023-11-30 12:15:39 25 4
gpt4 key购买 nike

我有一个名为“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() 会自动关闭连接。不过现在好像没有关闭。你能赐教吗?谢谢。

最佳答案

CommandBehavior.CloseConnection 来自 MSDN

When the command is executed, the associated Connection object is closed when the associated DataReader object is closed.

因此只有当您关闭 DataReader 时,连接才会关闭。

关于c# - SQLDataReader 和 CommandBehaviour.CloseConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7023823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com