Does.net SqlCommand.ExecuteReader close the connection?

In this sentence:

myCommand.ExecuteReader(CommandBehavior.CloseConnection) 

does the connection close in case of an exception?

+4
source share
3 answers

There are many ways a team can go wrong.

Ultimately, this is the Close method for a data reader that closes the connection if nothing has happened before.

If there is an exception that occurs inside the ExecuteReader or any of its called methods before the actual DataReader is created, then no, the connection will not be closed.

In case of an exception, I do not trust him to close the connection.

+3
source

The safest way to make a "normal" request is

 using (var conn = new SqlConnection("...")) { conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = "..."; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { // ... } } } } 

Exceptions can be detected outside this code.

+7
source

It depends on where the exception occurs!

If you structure try try correctly, this will be fine.

For instance:

 SqlCommand myCommand = new SqlCommand(); try { myCommand.dostuff(); } catch(Exception ex) { // display error message } finally { myCommand.ExecuteReader(CommandBehavior.CloseConnection); } 

If the line: myCommand.ExecuteReader (CommandBehavior.CloseConnection) fails (perhaps the database has dropped?), Then the connection cannot be closed programmatically.

0
source

All Articles