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

查看:337
本文介绍了在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天全站免登陆