Link to home
Start Free TrialLog in
Avatar of John Porter
John PorterFlag for United States of America

asked on

Can't close connection to database from finally block

Pertains to C#...
Hello,
I am unable to close the connection to my database from the finally block or another method. I am using the following code:

string ConStr = LoginFirst.Connection;
string SQL = "SELECT * FROM tableA";
         
try
   {
      OleDbConnection Conn = new OleDbConnection(ConStr);                  
      leDbCommand1 = new OleDbCommand(SQL, Conn);
      da = new OleDbDataAdapter();
      da.SelectCommand = oleDbCommand1;
      oleDbCb = new OleDbCommandBuilder(da);
      da.Fill(dataSet1, "Stats");
      dataGrid1.SetDataBinding(dataSet1, "Stats");

      }
      catch
      {
         //error handling code here                  
      }
      finally
      {
         //Want to close the DabtaBase connection here.  da.Close does not work here
                      
      }

I am also calling da.Update(dataSet1, "Stats"); from within another method. da.Close does not work here either.

Thanks
ASKER CERTIFIED SOLUTION
Avatar of sabeesh
sabeesh
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Bob Learned
If you are using C# 2005, then you can include a 'using' block that will simplify this a lot.

Bob
Hi,

You are not opening the connection with the database anywhere to close it.... And the OleDbDataAdapter does not contain any member as 'Close'

Hi,

Try this:

string ConStr = LoginFirst.Connection;
string SQL = "SELECT * FROM tableA";
OleDbConnection Conn;
         
try
   {
      Conn = new OleDbConnection(ConStr);
      Conn.Open();          
      leDbCommand1 = new OleDbCommand(SQL, Conn);
      da = new OleDbDataAdapter();
      da.SelectCommand = oleDbCommand1;
      oleDbCb = new OleDbCommandBuilder(da);
      da.Fill(dataSet1, "Stats");
      dataGrid1.SetDataBinding(dataSet1, "Stats");

      }
      catch
      {
         //error handling code here                  
      }
      finally
      {
         //Want to close the DabtaBase connection here.  da.Close does not work here

        Conn.Close();              
      }