473,385 Members | 1,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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 DatabaseConnection 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.ExecTimeOut=10;
NuclearWeapon.Launch=True;
OhWhatIHaveDone();

Feb 9 '06 #1
8 11864
> 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 DatabaseConnection 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.ExecuteNonQuery();
}
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.ExecuteNonQuery();
}
finally
{
cmd.Connection.Close();
}

can be written as:

using(SqlConnection 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(SqlConnection connection = new SqlConnection())
using(SqlCommand 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 DatabaseConnection 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.ExecuteNonQuery();
}
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 DatabaseConnection 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.ExecuteNonQuery();
}
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 DatabaseConnection 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.SqlClient;
using System.ComponentModel;

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

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

/// <summary>
/// Opens the connection with the SQL Server database
/// </summary>
public void OpenConnection()
{
sSQLConn =
System.Configuration.ConfigurationSettings.AppSett ings["DBConnectionString"];
sSQLConn +=
System.Configuration.ConfigurationSettings.AppSett ings["DBUserName"];
sSQLConn +=
System.Configuration.ConfigurationSettings.AppSett ings["DBServerName"];
SQLConnection = new SqlConnection(sSQLConn);
SQLConnection.Open();
}

/// <summary>
/// Closes the opened connection
/// </summary>
public void CloseConnection()
{
if(SQLConnection.State == ConnectionState.Open)
{
SQLConnection.Close();
SQLConnection.Dispose();
this.Dispose();
}
}

public void Dispose()
{
component.Dispose();
GC.SuppressFinalize(this);
}
}
}

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

=========
NuclearWeapon.ExecTimeOut=10;
NuclearWeapon.Launch=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 DatabaseConnection 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.SqlClient;
using System.ComponentModel;

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

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

/// <summary>
/// Opens the connection with the SQL Server database
/// </summary>
public void OpenConnection()
{
sSQLConn =
System.Configuration.ConfigurationSettings.AppSett ings["DBConnectionString"];
sSQLConn +=
System.Configuration.ConfigurationSettings.AppSett ings["DBUserName"];
sSQLConn +=
System.Configuration.ConfigurationSettings.AppSett ings["DBServerName"];
SQLConnection = new SqlConnection(sSQLConn);
SQLConnection.Open();
}

/// <summary>
/// Closes the opened connection
/// </summary>
public void CloseConnection()
{
if(SQLConnection.State == ConnectionState.Open)
{
SQLConnection.Close();
SQLConnection.Dispose();
this.Dispose();
}
}

public void Dispose()
{
component.Dispose();
GC.SuppressFinalize(this);
}
}
}

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

=========
NuclearWeapon.ExecTimeOut=10;
NuclearWeapon.Launch=True;
OhWhatIHaveDone();

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

In "CloseConnection", 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.Component Module.

The reasone is, when we use "Dispose()" method of any object provided by
microsoft
it releases all resources used by "System.Component" internally. So if you
have some
10 objects created and never "Dispose()" method is called, if you create a
object of
"Component" from System.Component 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.ExecTimeOut=10;
NuclearWeapon.Launch=True;
OhWhatIHaveDone();
Feb 11 '06 #7
On Thu, 9 Feb 2006 20:39:11 -0800, Beau Peep
<Be******@discussions.microsoft.com> wrote:

[snip]
One comment Beau.
if(SQLConnection.State == ConnectionState.Open)
{
SQLConnection.Close();
SQLConnection.Dispose();
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(SqlConnection.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.ExecTimeOut=10;
NuclearWeapon.Launch=True;
OhWhatIHaveDone();

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

[snip]
One comment Beau.
if(SQLConnection.State == ConnectionState.Open)
{
SQLConnection.Close();
SQLConnection.Dispose();
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(SqlConnection.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
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...
6
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...
13
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
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...
8
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...
6
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 {...
3
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...
16
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...
7
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...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.