Declaring a global connection string in ASP.NET

Using and interacting with database in every ASP.NET projects in now necessary. You cannot make a big project without a database. I have myself made many projects of my own in which I have used Microsoft’s SQL Server for database functionality.

But whenever you want to a request to the database you need a connection string. A string which contains all the data required to log in to the server and retrieve the records. But writing your connection string every time you create a new SQL connection is a tedious job. In case, you have changed the server where the database is stored, you will need to change the connection strings in all places where you have declared it. Like for example:
Dim DBConnection As New System.Data.SqlClient.SQLConnection("Data Source=MyServerName;Initial Catalog=DatabaseBane;Persist Security Info=True;User ID=userid;Password=mypassword")

If you want to change anytime the connection string, you will need to change it all places. So it’s better to declare it globally in the Web.config file which is available in all ASP.NET projects. In the Web.config file of your project, inside the <configuration> tag add the following:

<connectionStrings>
  <add name="MyDBConnection" connectionString="Data Source=MyServerName;Initial Catalog=DatabaseBane;Persist Security Info=True;User ID=userid;Password=mypassword" providerName="System.Data.SqlClient" />
</connectionStrings>

After adding the above lines in the Web.config file, you can refer to this connection string by simply writing:

Dim DBConnection As New System.Data.SqlClient.SQLConnection(System.Configuration.ConfigurationManager.ConnectionStrings("MyDBConnection").ConnectionString)

In this way, it would be globally declared. So that a change in the Web.config file will change it everywhere else. You can import the namespaces used here (since they are so long to type).

Advertisements

Your Thoughts -

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s