<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>eugene.K &#187; connection string</title>
	<atom:link href="http://ekdd.co.il/tag/connection-string/feed/" rel="self" type="application/rss+xml" />
	<link>http://ekdd.co.il</link>
	<description>web developer to web developers</description>
	<lastBuildDate>Tue, 22 Sep 2009 06:05:41 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>HOWTO: Properly connect to MSSQL database</title>
		<link>http://ekdd.co.il/howto-properly-connect-to-mssql-database/</link>
		<comments>http://ekdd.co.il/howto-properly-connect-to-mssql-database/#comments</comments>
		<pubDate>Sat, 19 Sep 2009 19:20:07 +0000</pubDate>
		<dc:creator>eugene</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MSSQL]]></category>
		<category><![CDATA[connection string]]></category>

		<guid isPermaLink="false">http://ekdd.co.il/?p=130</guid>
		<description><![CDATA[There are many ways you can connect to a database in ASP.NET, the way i’m going to explain here based on “try and error” during my development years. I will try to explain why i do each step and what errors i had in the past so you may prevent these in your web applications. [...]]]></description>
			<content:encoded><![CDATA[<p>There are many ways you can connect to a database in ASP.NET, the way i’m going to explain here based on “try and error” during my development years. I will try to explain why i do each step and what errors i had in the past so you may prevent these in your web applications. Experienced programmer should know each of these steps and may disagree so discussion is open to debate.</p>
<p><span id="more-130"></span></p>
<p><strong>What will you gain from using this technique ?</strong></p>
<ol>
<li>Organized in one place connection strings will prevent you from searching and replacing every time you change connection string or its name.</li>
<li>You will always have a connection closed and disposed from memory even if there was an error which prevented you from getting to the line where Sqlconnection is closed and disposed from memory.</li>
</ol>
<p><strong>Step one — Keep all connection string at one place<br />
</strong></p>
<p>Instead of hard coding every single place you connect to database you can set connection string value inside of web.config or a class. There is no rule where set connection string better in a class or web.config but any ASP.NET developer will first look at ConnectionStrings section of web.config so it would be better to keep connection strings where they belong to.</p>
<pre class="brush: xml">

&lt;connectionStrings&gt;
&lt;add name=&quot;Dismark&quot; connectionString=&quot;Data Source=.\sqlexpress;Initial Catalog=Dismark;Integrated Security=True;Pooling=False&quot; providerName=&quot;Sytem.Data.SqlClient&quot;/&gt;
&lt;add name=&quot;Support&quot; connectionString=&quot;Data Source=.\sqlexpress;Initial Catalog=Support;Integrated Security=True;Pooling=False&quot; providerName=&quot;Sytem.Data.SqlClient&quot;/&gt;
&lt;/connectionStrings&gt;
</pre>
<p>As you can see there are two database connection strings, it is important to name databases and give  connection string names according to what they represent. “Dismark” is an application name so i name the database and connection string the same name so in two month i won’t be needed to guess what “ConnectionString1” means. “Support” is a centralized database for costumer ticket support system because the client has few applications while it is much easier to work with centralized support ticket system rather have one per application. So each time you create an application for yourself or for a client ask yourself what whether are gonna be other applications or not because you can create external centralized Support, ErrorReports and Billing databases.</p>
<p><strong>Step two — Make connections easier to use by having a function to retrieve already opened SqlConnection.</strong></p>
<p>This step reduces amount of code you need to write each time you connect to database with your code. For example we will create a class inside of a App_Code folder named DB which will handle all our connections.</p>
<p>This is how your old code could look like</p>
<pre class="brush: c#">

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[&quot;Dismark&quot;].ConnectionString);
cn.Open();
// code goes here
cn.Close();
cn.Dispose();
}
}
</pre>
<p>Instead lets create a DB class with two functions, each function connects to specific database, opens a connection and returns to the caller.This way we will write less code each time we connect to database, it will be easier to change if for some reason we will change a database moved to another server or we will have to change connection string name.</p>
<pre class="brush: c#">

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

public class DB
{
public static SqlConnection connectToDismark()
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[&quot;Dismark&quot;].ConnectionString);
cn.Open();
return cn;
}
public static SqlConnection connectToSupport()
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[&quot;Support&quot;].ConnectionString);
cn.Open();
return cn;
}
}
</pre>
<p>This is a call to these functions from page where you connect to a database. As you can see there are less code to write and we don’t have to remember database’s exact name as Visual Studio’s intellisense helps us when we type DB class name.</p>
<pre class="brush: c#">
SqlConnection cn2 = DB.connectToDismark();
// code goes here
cn2.Close();
cn2.Dispose();
</pre>
<p><strong>Step 3 — Encapsulation of connection within using block<br />
</strong></p>
<p>As you see there are two methods remain, connection.Close() and connection.Dispose(). One obviously closes the connection to database and other one disposes it from memory. We need to keep in mind that sometimes we won’t reach those lines of code because of error of some kind (ie. bad input from user which cause an error to <a title="SqlCommand class" href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx" target="_blank">SqlCommand </a>object). Which means connection will remain open until Sql Server closes it. Not good practice as server may have limit or still use resources to keep the connection alive, instead of that we can encapsulate connection within using block which will automatically close() and dispose() connection when we leave its scope. Lets see how its done.</p>
<pre class="brush: c#">
using (SqlConnection cn3 = DB.connectToDismark())
{
// code goes here
}
</pre>
<p><a title="SqlConnection Class" href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx" target="_blank">Sqlconnection</a> class inherits from <a title="IDisposable Interface" href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" target="_blank">IDisposable</a> interface which allows to use it within using block, same goes for <a title="SqlDataReader Class" href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx" target="_blank">SqlDataReader</a> class.</p>
<p>Much faster and secure isn’t it ?</p>
]]></content:encoded>
			<wfw:commentRss>http://ekdd.co.il/howto-properly-connect-to-mssql-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
