Sameer Ahmed S
Sameer Ahmed S

Reputation: 1683

Connection not getting closed when SqlDataAdapter is used

After executing the Command using SqlDataAdapter, connection with the db is not getting closed. Let me know what needs to be done. Here is the code snippet

 DataSet dsResult = new DataSet("Result");
            SqlCommand selectCommand = new SqlCommand();
            if (_datasource.DataType == DataType.SqlText)
            {
                selectCommand = GenerateCommand(_datasource.DataType,_sqlquery);
            }
            else
            {
                selectCommand = GenerateCommand(_datasource.DataType, _datasource.DataObjectName, _fieldNames, _filters);
            }

            SqlDataAdapter da = new SqlDataAdapter(selectCommand.CommandText, _datasource.ConnectionString);
            da.Fill(dsResult);



            dataset = dsResult;

Tried explicity closing the connection like da.SelectCommand.Connection.Close(). But issue did not get fixed. Also tried the following still issue not fixed

using(SqlDataAdapter da = new SqlDataAdapter(selectCommand.CommandText, _datasource.ConnectionString))
{
                da.Fill(dsResult);
}

Let me know what can be done to release the session.

Upvotes: 1

Views: 2234

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460158

The Fill method retrieves rows from the data source using the SELECT statement specified by an associated SelectCommand property. The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

http://msdn.microsoft.com/en-us/library/377a8x4t.aspx

I highlighted you case. You haven't opened the connection, so the DataAdapter will open it automatically for you and close it when it's finished.

Edit: If you want to manage the connection yourself, you should always close it immediately you're finished with it.

Therefor you could use the using-statement which disposes/closes it (even in case of an exception).

using(var con = new SqlConnection(_datasource.ConnectionString))
{
    using(var da = new SqlDataAdapter(selectCommand.CommandText, con))
    {
        con.Open(); // not needed but ...
        da.Fill(dsResult); // will not close the conection now
    }
} // will close the connection

Edit2: Closing a conection does not mean that it is closed physically. It is just a hint for the Connection-Pool that it can be used again.

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

Upvotes: 2

Related Questions