简体   繁体   English

C# SqlDataReader 关闭方法

[英]C# SqlDataReader close method

Which of these methods is better for closing SqlDataReader :以下哪种方法更适合关闭SqlDataReader

 SqlDataReader reader = comm.ExecuteReader();

 while (reader.Read())
 {
 }
 reader.Close();
 reader.Dispose();

or或者

SqlDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
}

or there are another further closing methods?还是有另一种进一步的关闭方法?

The correct way of handling this is the using statement:处理这个问题的正确方法是using语句:

using(SqlDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection)) {
    while (reader.Read())
    { 

    }
}

This way the object gets disposed correctly (and you don't need to call Close() ).这样 object 就可以正确处理(并且您不需要调用Close() )。

A using statement is the best practice in such situations from my experience.根据我的经验,在这种情况下, using语句是最佳实践。 It makes sure the connection is properly closed even if an exception happens somewhere inside.即使内部某处发生异常,它也可以确保正确关闭连接。

using (SqlDataReader reader = comm.ExecuteReader())
{
    while (reader.Read())
    {
        //Do stuff...
    }
}

Of course you could do the same with a try { } finally { } , which is what the using statement does internally.当然你也可以用try { } finally { }来做同样的事情,这是using语句在内部所做的。 I found it's generally a good idea to get in the habit of always handling readers via the using statement to avoid the possibility of leaked connections.我发现养成始终通过using语句处理读者的习惯通常是一个好主意,以避免泄漏连接的可能性。

Use first scenario if you work with reader within one method and second one if you pass reader as return value (not within one scope).如果您在一个方法中使用 reader,则使用第一个场景,如果您将 reader 作为返回值(不在一个范围内)传递,则使用第二个场景。

the doc you need is this one: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.close.aspx您需要的文档是: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.close.aspx

To quote: "You must explicitly call the Close method when you are through using the SqlDataReader to use the associated SqlConnection for any other purpose."引用:“当您使用 SqlDataReader 将关联的 SqlConnection 用于任何其他目的时,您必须显式调用 Close 方法。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM