在迭代 DbDataReader 之前可以配置 DbCommand 吗?
我有一个简单的应用程序,需要执行某些查询来获取数据库架构信息。我编写了一个简单的方法,它执行查询并返回读取器,如下所示 -
public static DbDataReader ExecuteQuery(DbConnection connection,string sql)
{
DbCommand command = connection.CreateCommand();
command.CommandText = sql;
using(command)
{
return command.ExecuteReader();
}
}
调用代码确实关闭连接并适当地处理读取器和连接。
我的问题 - 在迭代阅读器之前处理命令实例(通过 using 块完成)是否可以/正确?我不希望关闭阅读器后填充任何 OUT 参数。 ADO.NET API 对此有任何严格的准则吗?
I have a simple application that needs to execute certain queries to get the database schema information. I have written a simple method that executes a query and returns a reader, something like this -
public static DbDataReader ExecuteQuery(DbConnection connection,string sql)
{
DbCommand command = connection.CreateCommand();
command.CommandText = sql;
using(command)
{
return command.ExecuteReader();
}
}
The calling code does close the connection and dispose the reader and connection appropriately.
My question - Is it ok/right to dipose the command instance (as is done via the using block) before iterating the reader? I do not expect any OUT parameters to be populated after closing the reader. Does the ADO.NET API have any strict guidelines regarding this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您将 using 块留在方法命令中时,命令将关闭并释放,如果您能够使用调用者的读取器,则意味着它仍然可以工作。
命令是针对连接执行语句的一种方法,但不保存任何数据,这就是它起作用的原因。只要连接打开,您就可以使用您的阅读器。
附言。还有一个很好的 ExecuteReader 重载,它指示 Reader 直接为您关闭连接,当连接像使用命令一样在本地创建而不是从外部传递时非常有用。
When you leave the using block in your method command is closed and disposed, if you are able to use the reader from the caller means it still work.
Commands are a mean to execute statements against a connection but do not hold any data this is the reason why this works. As long as the connection is open you can use your reader.
PS. there is also a nice overload of ExecuteReader which instructs the Reader to close the connection directly for you on disposal, useful when connection is created locally like you do with the command and not passed from outside.