问题描述
它是安全的这样写这个辅助方法?它会一直关闭连接?我understend如果一切顺利,它会,但会的ExecuteReader关闭连接,即使抛出?
公共静态的IEnumerable< DbDataRecord>的ExecuteSelect(字符串的CommandText,康涅狄格州的DbConnection)
{
使用(的DbCommand CMD = conn.CreateCommand())
{
cmd.CommandText =的CommandText;
conn.Open();
使用(DbDataReader读卡器= cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
的foreach(DbDataRecord在读者记录){收益回报记录; }
}
}
}
是的,即使它抛出一个异常,它会关闭连接。如果没有指定 CommandBehavior.CloseConnection
和关闭连接,您的电话code不能访问阅读器的内容。
另外从MSDN:
您应该确保读者被关闭,当你用它做。关于这一切的好处是,你得到了它包裹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:
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)始终密切联系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!