在 ExecuteReader() 中使用 CommandBehavior.CloseConnection 的用途/优势是什么

What is the use/advantage of using CommandBehavior.CloseConnection in ExecuteReader()(在 ExecuteReader() 中使用 CommandBehavior.CloseConnection 的用途/优势是什么)
本文介绍了在 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 的用途/优势是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)