威尔的ExecuteReader(CommandBehavior.CloseConnection)始终密切联系? [英] Will ExecuteReader(CommandBehavior.CloseConnection) always close connection?

查看:182
本文介绍了威尔的ExecuteReader(CommandBehavior.CloseConnection)始终密切联系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是安全的这样写这个辅助方法?它会一直关闭连接?我understend如果一切顺利,它会,但会的ExecuteReader关闭连接,即使抛出?

 公共静态的IEnumerable< D​​bDataRecord>的ExecuteSelect(字符串的CommandText,康涅狄格州的DbConnection)
    {
        使用(的DbCommand CMD = conn.CreateCommand())
        {
            cmd.CommandText =的CommandText;
            conn.Open();
            使用(DbDataReader读卡器= cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                的foreach(DbDataRecord在读者记录){收益回报记录; }
            }
        }
    }
 

解决方案

是的,即使它抛出一个异常,它会关闭连接。 如果没有指定 CommandBehavior.CloseConnection 和关闭连接,您的电话code不能访问阅读器的内容。

另外从MSDN:

  

在执行该命令,相关联的Connection对象   当相关DataReader对象被关闭关闭。

您应该确保读者被关闭,当你用它做。 关于这一切的好处是,你得到了它包裹using语句周围,你没有使用的try / catch /终于在这种情况下,读者将被关闭然后将关闭数据库连接。

Is it safe to write this helper method like this? Will it always close the connection? I understend if all goes well, it will, but will ExecuteReader close the connection even if it throws?

    public static IEnumerable<DbDataRecord> ExecuteSelect(string commandText, DbConnection conn)
    {
        using (DbCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = commandText;
            conn.Open();
            using (DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                foreach (DbDataRecord record in reader) { yield return record; }
            }
        }
    }

解决方案

Yes even if it throws an exception it will close the connection. If you do not specify CommandBehavior.CloseConnection and you close the connection, your calling code cannot access the contents of the reader.

Also from MSDN:

When the command is executed, the associated Connection object is closed when the associated DataReader object is closed.

You should ensure that the reader is closed when you are done with it. The nice thing about all of this is you've got it wrapped around a using statement and you aren't using try/catch/finally in this case the reader will be closed which then will close the database connection.

这篇关于威尔的ExecuteReader(CommandBehavior.CloseConnection)始终密切联系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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