Does SqlDataAdapter.Fill() always close the connection?

  • Thread starter Thread starter M
  • Start date Start date
M

M

Hi,

Does SqlDataAdapter always close the connection (assuming connection was
closed before calling Fill()), even if an exception occurs while calling
Fill()?

Example:
try
{
myDataAdapter.Fill(myDataTable);
}
catch
{
// display some error message or something
}

or should I do this instead

try
{
myDataAdapter.Fill(myDataTable);
}
catch
{
// display some error message or something
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}

Thanks.
 
SqlDataAdapter manages the connection itself, meaning it opens the connection
and it closes the connection. If, OTOH, you tell it the connection and you
open the connection yourself, it detects this and it will not close the connection.
So since you opened it you're responsible for closing it.

-Brock
DevelopMentor
http://staff.develop.com/ballen
 
The dataAdapter manages the connection so you don't have to close it. The
Adapter does all the work
 
Hi Brock,

In my example, I did not open the connection. I let SqlDataAdapter open the
connection. What I'm not sure though, is what happens if .Fill() generates
an exception. Will the adapter still close the connection or not? Maybe Fill
has its own try/catch/finally block and therefore will close the connection
in its own finally even if an error occurred; but that is what I'm not sure
about.

Thanks.
 
Here's the code in the DataAdapter. QuietOpen and QuietClose open and close
the connection as long as it wasn't already open when you call Fill:

try
{
try
{
DbDataAdapter.QuietOpen(connection1, out state1);
using (IDataReader reader1 = command.ExecuteReader(behavior
| CommandBehavior.SequentialAccess))
{
if (data is DataTable)
{
return this.Fill((DataTable) data, reader1);
}
return this.Fill((DataSet) data, srcTable, reader1,
startRecord, maxRecords);
}
}
finally
{
DbDataAdapter.QuietClose(connection1, state1);
}
}
catch
{
throw;
}

-Brock
DevelopMentor
http://staff.develop.com/ballen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top