3

How can I close Database connection forcefully?

The sample code I'm using to create connection is:

class Customer{
     private readonly Database _db;
      public Customer(){
            _db = = DatabaseFactory.CreateDatabase(_userSettings.ConnstringName);
       }

   .. stuff to use this connection..

}
KodeKreachor
  • 8,852
  • 10
  • 47
  • 64
Akhil
  • 1,421
  • 1
  • 16
  • 21

1 Answers1

1

Put the code (.. stuff to use this connection..) inside a using block, which will ensure the connection is closed. For example:

using (DbCommand command = _db.GetStoredProcCommand(sprocName, parameters))    
{

and:

using (IDataReader rdr = _db.ExecuteReader(command))
{

Using blocks are a nice way of ensuring resources are closed properly:

The using statement allows the programmer to specify when objects that use resources should release them.

Otherwise, you have to explicitly call the Close() method on the connection object:

if (command.Connection.State == ConnectionState.Open)
            command.Connection.Close();
Joe Ratzer
  • 18,176
  • 3
  • 37
  • 51
  • I can't do that because I m not creating the connection. the is used by **cmd = _db.GetStoredProcCommand(query)** or **_db.Get..SomeThing** or **_db._db.ExecuteReader / ExecuteDatase** – Akhil Apr 19 '11 at 14:01
  • You're right. I just updated the code snippet to reflect the real EL syntax. The benefit of a using block is the point. – Joe Ratzer Apr 19 '11 at 14:05
  • Another thing is when the Object ( this case Customer) get disposed all the resource consumed by Object ( may be the connection) get disposed ( connection get closed..) am I correct..? – Akhil Apr 19 '11 at 14:15
  • Not necessarily. Can you post some code so I can understand the context? – Joe Ratzer Apr 19 '11 at 14:22
  • @Joe R: can u pls take a look at [What is difference between Oracle session and Oracle Connection Or Both are the same..?] (http://stackoverflow.com/questions/5717927/what-is-difference-between-oracle-session-and-oracle-connection-or-both-are-the-s) – Akhil Apr 19 '11 at 14:26
  • Ok, you would need to make sure that the connection is properly closed. Just allowing Customer to go out of scope is not enough. I've added an answer to that question. – Joe Ratzer Apr 19 '11 at 16:39
  • any final solution with full source code sample working about it ? – Kiquenet Oct 30 '13 at 08:36