What is the use/advantage of using CommandBehavior.CloseConnection in ExecuteReader()(在 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 的用途/优势是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 ExecuteReader() 中使用 CommandBehavior.CloseConnection 的用途/优势是什么
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 使用 rss + c# 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
