HOWTO: Properly connect to MSSQL database

There are many ways you can con­nect to a data­base in ASP.NET, the way i’m going to explain here based on “try and error” dur­ing my devel­op­ment years. I will try to explain why i do each step and what errors i had in the past so you may pre­vent these in your web appli­ca­tions. Expe­ri­enced pro­gram­mer should know each of these steps and may dis­agree so dis­cus­sion is open to debate.

What will you gain from using this technique ?

  1. Orga­nized in one place con­nec­tion strings will pre­vent you from search­ing and replac­ing every time you change con­nec­tion string or its name.
  2. You will always have a con­nec­tion closed and dis­posed from mem­ory even if there was an error which pre­vented you from get­ting to the line where Sql­con­nec­tion is closed and dis­posed from memory.

Step one — Keep all con­nec­tion string at one place

Instead of hard cod­ing every sin­gle place you con­nect to data­base you can set con­nec­tion string value inside of web.config or a class. There is no rule where set con­nec­tion string bet­ter in a class or web.config but any ASP.NET devel­oper will first look at Con­nec­tion­Strings sec­tion of web.config so it would be bet­ter to keep con­nec­tion strings where they belong to.


<connectionStrings>
<add name="Dismark" connectionString="Data Source=.\sqlexpress;Initial Catalog=Dismark;Integrated Security=True;Pooling=False" providerName="Sytem.Data.SqlClient"/>
<add name="Support" connectionString="Data Source=.\sqlexpress;Initial Catalog=Support;Integrated Security=True;Pooling=False" providerName="Sytem.Data.SqlClient"/>
</connectionStrings>

As you can see there are two data­base con­nec­tion strings, it is impor­tant to name data­bases and give  con­nec­tion string names accord­ing to what they rep­re­sent. “Dis­mark” is an appli­ca­tion name so i name the data­base and con­nec­tion string the same name so in two month i won’t be needed to guess what “ConnectionString1” means. “Sup­port” is a cen­tral­ized data­base for cos­tumer ticket sup­port sys­tem because the client has few appli­ca­tions while it is much eas­ier to work with cen­tral­ized sup­port ticket sys­tem rather have one per appli­ca­tion. So each time you cre­ate an appli­ca­tion for your­self or for a client ask your­self what whether are gonna be other appli­ca­tions or not because you can cre­ate exter­nal cen­tral­ized Sup­port, Error­Re­ports and Billing databases.

Step two — Make con­nec­tions eas­ier to use by hav­ing a func­tion to retrieve already opened SqlConnection.

This step reduces amount of code you need to write each time you con­nect to data­base with your code. For exam­ple we will cre­ate a class inside of a App_Code folder named DB which will han­dle all our connections.

This is how your old code could look like


using System;
using System.Configuration;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Dismark"].ConnectionString);
cn.Open();
// code goes here
cn.Close();
cn.Dispose();
}
}

Instead lets cre­ate a DB class with two func­tions, each func­tion con­nects to spe­cific data­base, opens a con­nec­tion and returns to the caller.This way we will write less code each time we con­nect to data­base, it will be eas­ier to change if for some rea­son we will change a data­base moved to another server or we will have to change con­nec­tion string name.


using System;
using System.Configuration;
using System.Data.SqlClient;

public class DB
{
public static SqlConnection connectToDismark()
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Dismark"].ConnectionString);
cn.Open();
return cn;
}
public static SqlConnection connectToSupport()
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Support"].ConnectionString);
cn.Open();
return cn;
}
}

This is a call to these func­tions from page where you con­nect to a data­base. As you can see there are less code to write and we don’t have to remem­ber database’s exact name as Visual Studio’s intel­lisense helps us when we type DB class name.

SqlConnection cn2 = DB.connectToDismark();
// code goes here
cn2.Close();
cn2.Dispose();

Step 3 — Encap­su­la­tion of con­nec­tion within using block

As you see there are two meth­ods remain, connection.Close() and connection.Dispose(). One obvi­ously closes the con­nec­tion to data­base and other one dis­poses it from mem­ory. We need to keep in mind that some­times we won’t reach those lines of code because of error of some kind (ie. bad input from user which cause an error to Sql­Com­mand object). Which means con­nec­tion will remain open until Sql Server closes it. Not good prac­tice as server may have limit or still use resources to keep the con­nec­tion alive, instead of that we can encap­su­late con­nec­tion within using block which will auto­mat­i­cally close() and dis­pose() con­nec­tion when we leave its scope. Lets see how its done.

using (SqlConnection cn3 = DB.connectToDismark())
{
// code goes here
}

Sql­con­nec­tion class inher­its from IDis­pos­able inter­face which allows to use it within using block, same goes for Sql­DataReader class.

Much faster and secure isn’t it ?

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DotNetKicks
  • DZone
  • LinkedIn
  • StumbleUpon
  • Technorati
  • Live
  • PDF

Tags: connection string

Leave a comment