Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 Development Tools
 ASP.NET
 "The connection was not closed." error

Author  Topic 

Dev Null
Starting Member

39 Posts

Posted - 2008-06-09 : 15:59:12
Hi folks,

Working in C# with .Net 2.0, I'm getting the error:

System.InvalidOperationException: The connection was not closed. The
connection's current state is open.

at System.Data.ProviderBase.DbConnectionInternal.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)

at System.Data.SqlClient.SqlConnection.Open()

Which I find difficult to believe is the real problem, but maybe I'm missing something. DB access for this app is done through a single access class, which has two access methods - GetData and SetData - of the basic form:

public void GetData( string databaseName, string queryString, DataTable dataTable )
{
lock ( this )
{
dataTable.Locale = CultureInfo.InvariantCulture;
string connectString = m_connectString.Replace( "[DatabaseName]", databaseName );
SqlConnection connection = new SqlConnection( connectString );
SqlCommand selectCMD = null;
SqlDataAdapter dataAdapter = null;
try
{
selectCMD = new SqlCommand( queryString, connection );
selectCMD.CommandTimeout = CommandTimeout;
dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = selectCMD;

connection.Open();
dataAdapter.Fill( dataTable );
connection.Close();

}
catch ( SqlException ex )
// irrelevant error handling not being called
catch ( Exception ex )
// irrelevant error message which is being called to produce the error
finally
{
if ( connection.State != ConnectionState.Closed )
{
connection.Close();
}
}

}
}


So its creating a fresh connection, opening it immediately before use and closing it immediately after, and theres even a try-finally which should close it if anything goes wrong. SetData looks almost exactly the same. So how could the connection be getting left open?

(I am aware that the Open() and Close() calls should be irrelevant with Fill() - I didn't write this stuff, I'm just trying to fix it - but they should be harmless, right?)

Thanks for any help you can offer,

- rob.
   

- Advertisement -