I am using ADO.NET (.NET 1.1) in a legacy app. I know that DataAdapter.Fill() opens and closes connections if the connection hasn't been opened manually before it's given to the DataAdapter.
My question: Does it also close the connection if the .Fill() causes an Exception? (due to SQL Server cannot be reached, or whatever). Does it leak a connection or does it have a built-in Finally-clause to make sure the connection is being closed.
Code Example:
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter
Dim ds As New DataSet
cmd.Connection = New SqlConnection(strConnection)
cmd.CommandText = strSQL
da.SelectCommand = cmd
da.Fill(ds)
It does not close the connection. This example works and outputs the Id of "ARealTable"
Edit:
If you open the connection before hand (calling Open on the IDbConnection object), the IDataAdapter will not close it. However, if you allow the IDataAdapter to manage the connection wholly, it will be closed.
If the connection is open before the Fill() method is called, then no, the connection will not be closed by the DataAdapter.
However, if you do not explicitly open the connection, and instead let the DataAdapter open and close the connection within the Fill() command, then the connection will be closed on error.
This can be implied from multiple sources of documentation, including this one: Data Access Strategies Using ADO.NET and SQL
Further, this can be demonstrated in code by writing a routine that will error out and then checking the connection's State.
This code from a Windows Forms app proves it. The first message box will say "Open" and the second "Closed".