在 ExecuteReader() 中使用 CommandBehavior.CloseConnection 的用途/优势是什么 [英] What is the use/advantage of using CommandBehavior.CloseConnection in ExecuteReader()

查看:17
本文介绍了在 ExecuteReader() 中使用 CommandBehavior.CloseConnection 的用途/优势是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我什么是 CommandBehavior.CloseConnection 以及在 com.ExecuteReader(CommandBehavior.CloseConnection) 中将其作为参数传递的用途/好处是什么?

Can anyone tell me what is the CommandBehavior.CloseConnection and what is the use/benefit of passing this as a parameter in com.ExecuteReader(CommandBehavior.CloseConnection)?

推荐答案

读取数据读取器时需要打开连接,并且希望尽快关闭连接.通过指定 CommandBehavior.CloseConnection 在调用 ExecuteReader 时,请确保您的代码将在关闭数据读取器时关闭连接.

You need an open connection while reading a data reader, and you want to close connections as soon as you can. By specifying CommandBehavior.CloseConnection when calling ExecuteReader, you ensure that your code will close the connection when it closes the data reader.

但是您应该已经立即处理您的连接(不仅仅是关闭它们),在这种情况下,这样做最多只能获得边际(几乎可以肯定是无法衡量)的好处.

But you should already be disposing your connections immediately (not just closing them), in which case there's at best a marginal (almost certainly unmeasurable) benefit to doing this.

例如,此代码立即关闭其连接(并且执行任何其他需要处理它的工作),而不指定命令行为:

For example, this code closes its connection immediately (and performs whatever other work is required to dispose it), without specifying the command behavior:

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(commandText, connection))
{
    connection.Open();
    using (SqlDataReader reader = command.ExecuteReader()) 
    {
        while (reader.Read())
           // Do something with the rows
    }
}

这篇关于在 ExecuteReader() 中使用 CommandBehavior.CloseConnection 的用途/优势是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆