473,657 Members | 2,579 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

open and close database connection in classes

Hello All,
Like in C++ I tried to use constructor to open a database connection and
distructor to close the database connection, it now turns out that one
cannot create distrutors in C# classes.

Here is my code

public class DBLayer

{

private string strError;

private SqlConnection conn;

private SqlDataAdapter mySqlTagsAdapte r;

private string strQuery;

public DBLayer()

{

strQuery = "";

conn = new
SqlConnection(C onfigurationSet tings.AppSettin gs["ConnectionStri ng"]);

strError = "";

try

{

conn.Open();

}

catch (Exception ex)

{

strError = "Unable to open the database " + ex.ToString();

}

}

~DBLayer()

{

if (conn != null)

{

if (conn.State != ConnectionState .Closed)

{

try

{

conn.Close();

}

catch (Exception ex)

{

strError = "Unable to close the database " + ex.ToString();

};

}

}

}

}

Can you suggest how to sort out this issue now, I have already got lot of
classes and code that uses this approach and now the connections are not
being closed, can you please suggest a solution how to sort this out. How
can I close connection in the classes when the calling asp.net page ends
execution.

Regards,

Imran.
Aug 15 '06 #1
8 14553
Hi Imran,
One way to accomplish this by making a disposable object and use the
"using" construct. The idea is that the object's Dispose( ) method
will be called when the using block is exited (much like a dtor for a
stack object in C++).

John

Imran Aziz wrote:
Hello All,
Like in C++ I tried to use constructor to open a database connection and
distructor to close the database connection, it now turns out that one
cannot create distrutors in C# classes.

Here is my code

public class DBLayer

{

private string strError;

private SqlConnection conn;

private SqlDataAdapter mySqlTagsAdapte r;

private string strQuery;

public DBLayer()

{

strQuery = "";

conn = new
SqlConnection(C onfigurationSet tings.AppSettin gs["ConnectionStri ng"]);

strError = "";

try

{

conn.Open();

}

catch (Exception ex)

{

strError = "Unable to open the database " + ex.ToString();

}

}

~DBLayer()

{

if (conn != null)

{

if (conn.State != ConnectionState .Closed)

{

try

{

conn.Close();

}

catch (Exception ex)

{

strError = "Unable to close the database " + ex.ToString();

};

}

}

}

}

Can you suggest how to sort out this issue now, I have already got lot of
classes and code that uses this approach and now the connections are not
being closed, can you please suggest a solution how to sort this out. How
can I close connection in the classes when the calling asp.net page ends
execution.

Regards,

Imran.
Aug 15 '06 #2
Close connection manually (or use using statement for it)

PS: and forget about descructors in .net :)

--
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche


"Imran Aziz" wrote:
Hello All,
Like in C++ I tried to use constructor to open a database connection and
distructor to close the database connection, it now turns out that one
cannot create distrutors in C# classes.

Here is my code

public class DBLayer

{

private string strError;

private SqlConnection conn;

private SqlDataAdapter mySqlTagsAdapte r;

private string strQuery;

public DBLayer()

{

strQuery = "";

conn = new
SqlConnection(C onfigurationSet tings.AppSettin gs["ConnectionStri ng"]);

strError = "";

try

{

conn.Open();

}

catch (Exception ex)

{

strError = "Unable to open the database " + ex.ToString();

}

}

~DBLayer()

{

if (conn != null)

{

if (conn.State != ConnectionState .Closed)

{

try

{

conn.Close();

}

catch (Exception ex)

{

strError = "Unable to close the database " + ex.ToString();

};

}

}

}

}

Can you suggest how to sort out this issue now, I have already got lot of
classes and code that uses this approach and now the connections are not
being closed, can you please suggest a solution how to sort this out. How
can I close connection in the classes when the calling asp.net page ends
execution.

Regards,

Imran.
Aug 15 '06 #3
Hi,

You can have a destructor in C# too.

But that is another matter, you should keep your connection open the minimun
time possible ! , I would suggest you to just open/close the connection in
each method that you need it.
like

void DoSomething()
{
using (SqlConnection con = new SqlConnection(. .....) )
{
}
}

This will allow your app to scale. If you keep connections open you are
holding resources for nothing. ADO.NET use a connection pooling that handles
the connection status for you.
--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Imran Aziz" <im***@tb2.netw rote in message
news:e$******** ******@TK2MSFTN GP04.phx.gbl...
Hello All,
Like in C++ I tried to use constructor to open a database connection
and distructor to close the database connection, it now turns out that one
cannot create distrutors in C# classes.

Here is my code

public class DBLayer

{

private string strError;

private SqlConnection conn;

private SqlDataAdapter mySqlTagsAdapte r;

private string strQuery;

public DBLayer()

{

strQuery = "";

conn = new
SqlConnection(C onfigurationSet tings.AppSettin gs["ConnectionStri ng"]);

strError = "";

try

{

conn.Open();

}

catch (Exception ex)

{

strError = "Unable to open the database " + ex.ToString();

}

}

~DBLayer()

{

if (conn != null)

{

if (conn.State != ConnectionState .Closed)

{

try

{

conn.Close();

}

catch (Exception ex)

{

strError = "Unable to close the database " + ex.ToString();

};

}

}

}

}

Can you suggest how to sort out this issue now, I have already got lot of
classes and code that uses this approach and now the connections are not
being closed, can you please suggest a solution how to sort this out. How
can I close connection in the classes when the calling asp.net page ends
execution.

Regards,

Imran.


Aug 15 '06 #4
Thanks for the response, I am going to close them explicitly now.
"Michael Nemtsev" <Mi************ @discussions.mi crosoft.comwrot e in
message news:E1******** *************** ***********@mic rosoft.com...
Close connection manually (or use using statement for it)

PS: and forget about descructors in .net :)

--
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do
not
cease to be insipid." (c) Friedrich Nietzsche


"Imran Aziz" wrote:
>Hello All,
Like in C++ I tried to use constructor to open a database connection
and
distructor to close the database connection, it now turns out that one
cannot create distrutors in C# classes.

Here is my code

public class DBLayer

{

private string strError;

private SqlConnection conn;

private SqlDataAdapter mySqlTagsAdapte r;

private string strQuery;

public DBLayer()

{

strQuery = "";

conn = new
SqlConnection( ConfigurationSe ttings.AppSetti ngs["ConnectionStri ng"]);

strError = "";

try

{

conn.Open();

}

catch (Exception ex)

{

strError = "Unable to open the database " + ex.ToString();

}

}

~DBLayer()

{

if (conn != null)

{

if (conn.State != ConnectionState .Closed)

{

try

{

conn.Close() ;

}

catch (Exception ex)

{

strError = "Unable to close the database " + ex.ToString();

};

}

}

}

}

Can you suggest how to sort out this issue now, I have already got lot of
classes and code that uses this approach and now the connections are not
being closed, can you please suggest a solution how to sort this out. How
can I close connection in the classes when the calling asp.net page ends
execution.

Regards,

Imran.

Aug 15 '06 #5
Thanks for the response John, I am going to close them explicitly now.

"John Duval" <Jo********@gma il.comwrote in message
news:11******** **************@ m73g2000cwd.goo glegroups.com.. .
Hi Imran,
One way to accomplish this by making a disposable object and use the
"using" construct. The idea is that the object's Dispose( ) method
will be called when the using block is exited (much like a dtor for a
stack object in C++).

John

Imran Aziz wrote:
>Hello All,
Like in C++ I tried to use constructor to open a database connection
and
distructor to close the database connection, it now turns out that one
cannot create distrutors in C# classes.

Here is my code

public class DBLayer

{

private string strError;

private SqlConnection conn;

private SqlDataAdapter mySqlTagsAdapte r;

private string strQuery;

public DBLayer()

{

strQuery = "";

conn = new
SqlConnection( ConfigurationSe ttings.AppSetti ngs["ConnectionStri ng"]);

strError = "";

try

{

conn.Open();

}

catch (Exception ex)

{

strError = "Unable to open the database " + ex.ToString();

}

}

~DBLayer()

{

if (conn != null)

{

if (conn.State != ConnectionState .Closed)

{

try

{

conn.Close() ;

}

catch (Exception ex)

{

strError = "Unable to close the database " + ex.ToString();

};

}

}

}

}

Can you suggest how to sort out this issue now, I have already got lot of
classes and code that uses this approach and now the connections are not
being closed, can you please suggest a solution how to sort this out. How
can I close connection in the classes when the calling asp.net page ends
execution.

Regards,

Imran.

Aug 15 '06 #6
Hi,

"Imran Aziz" <im***@tb2.netw rote in message
news:O8******** ******@TK2MSFTN GP04.phx.gbl...
Thanks for the response, I am going to close them explicitly now.
The recommended coding is wrapping the conenction class with an using
statement, this will assure that even if an exception occur the connection
is closed.
--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Aug 15 '06 #7
Thanks for that, I will surly use this from now on, the issue at the moment
however is that I have got around 15 classes already using this technique,
the constructor opens the connections hence in order to use the using option
I will endup altering all methods which is quite a big task, so for now I am
just closing the connection making sure I close it in try/catch blocks as
well .

Thanks a lot,

Imran.
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us wrote
in message news:uo******** ******@TK2MSFTN GP03.phx.gbl...
Hi,

"Imran Aziz" <im***@tb2.netw rote in message
news:O8******** ******@TK2MSFTN GP04.phx.gbl...
>Thanks for the response, I am going to close them explicitly now.

The recommended coding is wrapping the conenction class with an using
statement, this will assure that even if an exception occur the connection
is closed.
--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Aug 15 '06 #8
Thank you very much for the detailed explanation, I am following this now.

Imran.

"Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us wrote
in message news:e8******** ******@TK2MSFTN GP04.phx.gbl...
Hi,

You can have a destructor in C# too.

But that is another matter, you should keep your connection open the
minimun time possible ! , I would suggest you to just open/close the
connection in each method that you need it.
like

void DoSomething()
{
using (SqlConnection con = new SqlConnection(. .....) )
{
}
}

This will allow your app to scale. If you keep connections open you are
holding resources for nothing. ADO.NET use a connection pooling that
handles the connection status for you.
--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Imran Aziz" <im***@tb2.netw rote in message
news:e$******** ******@TK2MSFTN GP04.phx.gbl...
>Hello All,
Like in C++ I tried to use constructor to open a database connection
and distructor to close the database connection, it now turns out that
one cannot create distrutors in C# classes.

Here is my code

public class DBLayer

{

private string strError;

private SqlConnection conn;

private SqlDataAdapter mySqlTagsAdapte r;

private string strQuery;

public DBLayer()

{

strQuery = "";

conn = new
SqlConnection( ConfigurationSe ttings.AppSetti ngs["ConnectionStri ng"]);

strError = "";

try

{

conn.Open();

}

catch (Exception ex)

{

strError = "Unable to open the database " + ex.ToString();

}

}

~DBLayer()

{

if (conn != null)

{

if (conn.State != ConnectionState .Closed)

{

try

{

conn.Close() ;

}

catch (Exception ex)

{

strError = "Unable to close the database " + ex.ToString();

};

}

}

}

}

Can you suggest how to sort out this issue now, I have already got lot of
classes and code that uses this approach and now the connections are not
being closed, can you please suggest a solution how to sort this out. How
can I close connection in the classes when the calling asp.net page ends
execution.

Regards,

Imran.



Aug 15 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2562
by: C Sharp beginner | last post by:
I'm sorry about this verbose posting. This is a follow-up to my yesterday's posting. Thanks William for your reply. I understand it is a good practice to open connections as late as possible and close them as early as possible. My requirement is as follows: I'm developing a class library that will be instantiated by a COM component. My class library contains functions that perform lot of mathematical calculations and read a lot of data...
4
2467
by: Macca | last post by:
Hi, I have an windows forms application that accesses a SQL database I have a few questions as to connecting to the database. This application will run 24 hours a day. It is a monitoring application and will store events that happen in the database (These events happen randomly without pattern, between 10-50 a day) . There are a number of situations where the database is accessed.
2
1882
by: Michael | last post by:
Hello, In my past ASP pages, at the top I used an include file to open an ado connection for the entire page, then at the bottom, I would have another include file to close the connection. Now that I'm moving to .NET, and using ado.net as well, does anyone have any ideas to accomplish this for asp.net. I'd like for it to be as much behind the scenes as possible, hopefully so I'll never have to look at statements like...
4
3970
by: mescano | last post by:
I am currently implementing a singleton pattern for accessing a database. Is it advisable to close the connection to the database at all -- thus leaving it open or should it be closed. If closed, when should I it close it -- after the execution of the each command to the database? If leaving open, what impacts does it have. Imagining that it is one connection to the database. Thanks, mescano
20
7201
by: fniles | last post by:
I am using VB.NET 2003, SQL 2000, and SqlDataReader. As I read data from tblA, I want to populate tblB. I use SQLDataReader for both tables. I do not use thread. When I ExecuteReader on tblB, I get the error "There is already an open DataReader associated with this Connection which must be closed first." How can I fix this error ? For each DataReader, do I want to open and close the connection (in this case adoCon) to avoid this error ?...
5
3384
by: Usman Jamil | last post by:
Hi I've a class that creates a connection to a database, gets and loop on a dataset given a query and then close the connection. When I use netstat viewer to see if there is any connection open left, I always see that there are 2 connections open and in "ESTABLISHED" state. Here is the piece of code that I'm using, please tell where I'm doing it wrong. Since this class is being used at many placed in my actual web based application that...
6
4724
by: =?Utf-8?B?RyBIdXN0aXM=?= | last post by:
I am creating a new MS Access DB in code, which works fine. I then try to open it & set a password. I keep getting an error that the DB is already open by my machine's Admin account. In reality it is not actually open. Here is a look at my code for creating & then setting the Password. Dim ADOXcat As New ADOX.Catalog sCreateString = "Provider=" & Provider & ";Data Source=" & DatabaseFullPath Try ADOXcat.Create(sCreateString)
2
1921
by: Tony Johansson | last post by:
Hello! How does this connection pool function actually ? As I have been told is that when the connection is returned to the pool the connection to the database is still open. What you do is that you just return a still open connection to the pool. When I open a connection I get an already open connection to the database. Is this correct understood ?
20
5591
by: Author | last post by:
a .net 1.1 app has a class whose constructor opens a db connection to sql svr two thousand. this class has more than a dozen of methods. most of them don't do db stuff. I am wondering if this design is going to be a problem, bcoz each time this class is instantiated, a db conn is open. The worst thing is that I haven't seen anywhere in the code the db conn is closed. I write about this bcoz I see that this app leaves more than one...
0
8392
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8730
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6163
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4151
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4301
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1950
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.