473,700 Members | 2,842 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SQL Connection Example

Hello

Can any one show me whats the best way to open the SQL connection?.

I am creating a ClassLibray (.dll) file, Methods, Structures, Enumerations are
created in this dll file.

Here we have more than 1000 customers connected at the same time. I have
created a DatabaseConnect ion Class and I am using it in all modules in that
dll.
This is a web project. can any one show me how to use SQL connection the dll
file and used in the modules, so it should not slow up the process for the
logged
in users.

tanks for time. (its a exigency)
--
=========
NuclearWeapon.E xecTimeOut=10;
NuclearWeapon.L aunch=True;
OhWhatIHaveDone ();

Feb 9 '06 #1
8 11884
> Hello

Can any one show me whats the best way to open the SQL connection?.

I am creating a ClassLibray (.dll) file, Methods, Structures, Enumerations
are created in this dll file.

Here we have more than 1000 customers connected at the same time. I have
created a DatabaseConnect ion Class and I am using it in all modules in that
dll.
This is a web project. can any one show me how to use SQL connection the dll
file and used in the modules, so it should not slow up the process for the
logged
in users.

tanks for time. (its a exigency)


Especially for a webapplication: Open() as late as possible, Close() as
soon as possible, preferably within the "finally" of a
try(/catch)/finally block.

Something like:

try
{
cmd.Connection. Open();
cmd.ExecuteNonQ uery();
}
finally
{
cmd.Connection. Close();
}

This way the connections are put back in the connection-pool as soon as
possible, so they can be re-used by other database calls (maybe from
other users).

Hans Kesting
Feb 9 '06 #2
I agree with Hans about keeping the connection utilized for a short as
possible. A nice keyword in C#, the "using" keyword, can be used to save you
from having to call Close in a finally. Instead the using statement
guarantees that the Dispose method is called when you go outside of the scope
of the {}, even in the case when an exceptio is thrown, for example:

try
{
cmd.Connection. Open();
cmd.ExecuteNonQ uery();
}
finally
{
cmd.Connection. Close();
}

can be written as:

using(SqlConnec tion connection = new SqlConnection() )
{
//initialize conenction settings

connection.Open ();

//do work
}

when the using brace is exited Dispose is called on the conenction, Dispose
internally will call Close and release your connection back to the connection
pool.

You can also stack using statements for easier readability, rather than
embedding them inside one another, like:

using(SqlConnec tion connection = new SqlConnection() )
using(SqlComman d command = new SqlCommand())
{
}

Hope that helps
Mark Dawson
http://www.markdawson.org
"Hans Kesting" wrote:
Hello

Can any one show me whats the best way to open the SQL connection?.

I am creating a ClassLibray (.dll) file, Methods, Structures, Enumerations
are created in this dll file.

Here we have more than 1000 customers connected at the same time. I have
created a DatabaseConnect ion Class and I am using it in all modules in that
dll.
This is a web project. can any one show me how to use SQL connection the dll
file and used in the modules, so it should not slow up the process for the
logged
in users.

tanks for time. (its a exigency)


Especially for a webapplication: Open() as late as possible, Close() as
soon as possible, preferably within the "finally" of a
try(/catch)/finally block.

Something like:

try
{
cmd.Connection. Open();
cmd.ExecuteNonQ uery();
}
finally
{
cmd.Connection. Close();
}

This way the connections are put back in the connection-pool as soon as
possible, so they can be re-used by other database calls (maybe from
other users).

Hans Kesting

Feb 9 '06 #3
On Thu, 09 Feb 2006 13:13:48 +0100, "Hans Kesting"
<ne***********@ spamgourmet.com > wrote:
Hello

Can any one show me whats the best way to open the SQL connection?.

I am creating a ClassLibray (.dll) file, Methods, Structures, Enumerations
are created in this dll file.

Here we have more than 1000 customers connected at the same time. I have
created a DatabaseConnect ion Class and I am using it in all modules in that
dll.
This is a web project. can any one show me how to use SQL connection the dll
file and used in the modules, so it should not slow up the process for the
logged
in users.

tanks for time. (its a exigency)


Especially for a webapplication: Open() as late as possible, Close() as
soon as possible, preferably within the "finally" of a
try(/catch)/finally block.

Something like:

try
{
cmd.Connection. Open();
cmd.ExecuteNonQ uery();
}
finally
{
cmd.Connection. Close();
}

This way the connections are put back in the connection-pool as soon as
possible, so they can be re-used by other database calls (maybe from
other users).

Hans Kesting

I'm currently assigned to do improvements on a web app that does
exactly what Beau says he has done. One of those *critical*
improvements is to remove the code from all of the places it was done
and open and close connections only as long as they are needed.

Your instructions to Beau are correct.

Otis Mukinfus
http://www.otismukinfus.com
http://www.tomchilders.com
Feb 9 '06 #4
Thank you Hans Kesting, Mark R. Dawson and Otis Mukinfus for replying to my
post

Here i have placed my sample DatabaseConnect ion Class code exactly what i have
writte. please look to it and let me know your valuable suggestions on this,
which point to improve and stuff like that. Let me know all what you have to
say.

using System;
using System.Data;
using System.Data.Sql Client;
using System.Componen tModel;

namespace GREW
{
/// <summary>
/// DatabaseConnect ion Class, used to establish the connection with the SQL
server
/// </summary>
class DatabaseConnect ion : IDisposable
{
Component component = new Component();

public SqlConnection SQLConnection;
string sSQLConn;
internal DatabaseConnect ion()
{
//
// TODO: Add constructor logic here
//
}

/// <summary>
/// Opens the connection with the SQL Server database
/// </summary>
public void OpenConnection( )
{
sSQLConn =
System.Configur ation.Configura tionSettings.Ap pSettings["DBConnectionSt ring"];
sSQLConn +=
System.Configur ation.Configura tionSettings.Ap pSettings["DBUserName "];
sSQLConn +=
System.Configur ation.Configura tionSettings.Ap pSettings["DBServerNa me"];
SQLConnection = new SqlConnection(s SQLConn);
SQLConnection.O pen();
}

/// <summary>
/// Closes the opened connection
/// </summary>
public void CloseConnection ()
{
if(SQLConnectio n.State == ConnectionState .Open)
{
SQLConnection.C lose();
SQLConnection.D ispose();
this.Dispose();
}
}

public void Dispose()
{
component.Dispo se();
GC.SuppressFina lize(this);
}
}
}

I will be waiting fo your responses. please do reply. And Thanks once again
for your precious time.

=========
NuclearWeapon.E xecTimeOut=10;
NuclearWeapon.L aunch=True;
OhWhatIHaveDone ();
Feb 10 '06 #5
> Thank you Hans Kesting, Mark R. Dawson and Otis Mukinfus for replying to my
post

Here i have placed my sample DatabaseConnect ion Class code exactly what i
have writte. please look to it and let me know your valuable suggestions on
this, which point to improve and stuff like that. Let me know all what you
have to say.

using System;
using System.Data;
using System.Data.Sql Client;
using System.Componen tModel;

namespace GREW
{
/// <summary>
/// DatabaseConnect ion Class, used to establish the connection with the SQL
server
/// </summary>
class DatabaseConnect ion : IDisposable
{
Component component = new Component();

public SqlConnection SQLConnection;
string sSQLConn;
internal DatabaseConnect ion()
{
//
// TODO: Add constructor logic here
//
}

/// <summary>
/// Opens the connection with the SQL Server database
/// </summary>
public void OpenConnection( )
{
sSQLConn =
System.Configur ation.Configura tionSettings.Ap pSettings["DBConnectionSt ring"];
sSQLConn +=
System.Configur ation.Configura tionSettings.Ap pSettings["DBUserName "];
sSQLConn +=
System.Configur ation.Configura tionSettings.Ap pSettings["DBServerNa me"];
SQLConnection = new SqlConnection(s SQLConn);
SQLConnection.O pen();
}

/// <summary>
/// Closes the opened connection
/// </summary>
public void CloseConnection ()
{
if(SQLConnectio n.State == ConnectionState .Open)
{
SQLConnection.C lose();
SQLConnection.D ispose();
this.Dispose();
}
}

public void Dispose()
{
component.Dispo se();
GC.SuppressFina lize(this);
}
}
}

I will be waiting fo your responses. please do reply. And Thanks once again
for your precious time.

=========
NuclearWeapon.E xecTimeOut=10;
NuclearWeapon.L aunch=True;
OhWhatIHaveDone ();

I'm not sure why you would need that "component" here.

In "CloseConnectio n", you might want to check if the connection is not
"null".

In "Dispose", also call CloseConnection .

Hans Kesting
Feb 10 '06 #6
Hello Hans Kesting

[AS OF MY KNOWLEDGE]

Actually, I am creating a new instance of the "Component" from the
System.Componen t Module.

The reasone is, when we use "Dispose()" method of any object provided by
microsoft
it releases all resources used by "System.Compone nt" internally. So if you
have some
10 objects created and never "Dispose()" method is called, if you create a
object of
"Component" from System.Componen t and if you call "Dispose()" method there,
all
other 10 object's resources are released along with "Component' s" resources
too.

So I have created a object of that there and disposing it in my own dispose
method.
So i dont have to worry about the other object creations.

What actually you thought on that "Component" object? Is there any better
way to
create the class file for database connection other that this?

Thanks for your time in replying back to me Hans Kesting.

Hope to see your response as soon.
--
=========
NuclearWeapon.E xecTimeOut=10;
NuclearWeapon.L aunch=True;
OhWhatIHaveDone ();
Feb 11 '06 #7
On Thu, 9 Feb 2006 20:39:11 -0800, Beau Peep
<Be******@discu ssions.microsof t.com> wrote:

[snip]
One comment Beau.
if(SQLConnectio n.State == ConnectionState .Open)
{
SQLConnection.C lose();
SQLConnection.D ispose();
this.Dispose();
}


In the above code you are closing the connection only if it is open.
Since connections can be in other states I check for

if(SqlConnectio n.State != ConnectionState .Closed)
{
// do closing code here
}

Doing so assures that you really did get it closed, even if it's in
another state.

Otis Mukinfus
http://www.otismukinfus.com
http://www.tomchilders.com
Feb 11 '06 #8
Thank you , Otis Mukinfus.

I implemented your suggestion of the code on closing connection and made it
exactly as you said.

Is there any thing you see more from the point of improvement? If yes, let
me know.

Thanks a lot for your valuable suggestion.
--
=========
NuclearWeapon.E xecTimeOut=10;
NuclearWeapon.L aunch=True;
OhWhatIHaveDone ();

"Otis Mukinfus" wrote:
On Thu, 9 Feb 2006 20:39:11 -0800, Beau Peep
<Be******@discu ssions.microsof t.com> wrote:

[snip]
One comment Beau.
if(SQLConnectio n.State == ConnectionState .Open)
{
SQLConnection.C lose();
SQLConnection.D ispose();
this.Dispose();
}


In the above code you are closing the connection only if it is open.
Since connections can be in other states I check for

if(SqlConnectio n.State != ConnectionState .Closed)
{
// do closing code here
}

Doing so assures that you really did get it closed, even if it's in
another state.

Otis Mukinfus
http://www.otismukinfus.com
http://www.tomchilders.com

Feb 12 '06 #9

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

Similar topics

4
17720
by: Fuzzyman | last post by:
In a nutshell - the question I'm asking is, how do I make a socket conenction go via a proxy server ? All our internet traffic has to go through a proxy-server at location 'dav-serv:8080' and I need to make a socket connection through it. The reason (with code example) is as follows : I am hacking "Tiny HTTP Proxy" by SUZUKI Hisao to make an http proxy that modifies URLs. I haven't got very far - having started from zero knowledge of...
6
1623
by: charliewest | last post by:
I have developed an application for WM 2003, which frequently transacts with a sql server ce 2.0 database. I have several procedures which utilize the following code: cn = new SqlCeConnection(@"<< sdf file >>"); cn.Open(); cmd = new SqlCeCommand(<< sql string >>, cn); cmd.ExecuteNonQuery(); cn.Close()
13
1888
by: Larry | last post by:
Hi I have asp.net programs. I used a very simple data transfer method by using URLs ¡°First.aspx¡± contents a line to send data to the ¡°second.aspx¡± page, for
2
3490
by: Bryan | last post by:
Hello, I'm just starting to develop in asp.net and i have a question about using a database connection globally in my app. I have set up the procedures for getting all my connection string info which each page will use, but my question relates to how to use the database connection i create in all my classes. I have a database class, in a separate namespace and file, i created that handles all the connection opening, executing statements...
8
2153
by: Pierson C | last post by:
I am developing on a website that is utilizing SQL Server 2000. Shortly after deploying the site, we began having timeout issues due to the max connections. 1st instinct was to diligently tidy up our connections. We did so by encapsulating with the using statement. Ex: using (SqlConnection myConnection = new SqlConnectionConfigurationSettings.AppSettings))
6
10981
by: M | last post by:
Hi, Does SqlDataAdapter always close the connection (assuming connection was closed before calling Fill()), even if an exception occurs while calling Fill()? Example: try { myDataAdapter.Fill(myDataTable);
3
10291
by: Martin B | last post by:
Hallo! I'm working with C# .NET 2.0, implementing Client/Server Applications which are connecting via Network to SQL-Server or Oracle Databases. To stay independent from the underlaying Database I use System.Data.Common.DBConnection and .DBCommand. How can I keep aware from connection losses (network not availeable, db-server not available...)? Are there any strategies to detect this broken connections, and how can I
16
2866
by: crbd98 | last post by:
Hello All, Some time ago, I implemented a data access layer that included a simple connectin pool. At the time, I did it all by myself: I created N connections, each connection associated with a worker thread that would execute the db commands. The pool was fixed and all the connections were created when the db access class was instantiated. The connections remained opened during the whole execution. If a connection was not available...
7
7480
by: Bill Nguyen | last post by:
I have this connection string using ODBC DSN Dim FactorJaco As String = "dsn=jaco;catalog=factor;uid=user;pwd=passord" This requires an ODBC DSN (jaco) at every client PC. I need to use DSN-less connection for terminal server setup. Any help is greatly appreciated.
0
8641
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
9060
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...
1
8958
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8912
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
6557
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
5897
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
4396
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
4650
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3082
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.