Is it good to dip DbCommand before iterating DbDataReader

I have a simple application that must fulfill certain queries in order to get information about the database schema. I wrote a simple method that executes a request 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 closes the connection and correctly manages the reader and the connection.

My question is: is it normal / correct to disperse the instance of the command (how is this done using the use block) before repeating the read? I do not expect any OUT parameters to be filled after the reader is closed. Does the ADO.NET API have any strict rules regarding this?

+6
source share
1 answer

When you leave the use block in your command, the method is closed and deleted, if you can use the reader from the caller, it still works.

Commands are a means of executing statements regarding a connection, but do not contain any data, which is why it works. While the connection is open, you can use your reader.

PS. there is also a good ExecuteReader overload, which instructs Reader to close the connection directly at your disposal, useful when the connection is created locally, as you do with the command, and not transmitted from the outside.

0
source

Source: https://habr.com/ru/post/899764/


All Articles