Post navigation

A Beginners Guide to the Connection String

One of the most misunderstood items, using ASP.Net, and some of the most asked questions, are about Connection Strings – the way in which you connect to the database. Any time you connect to a database, a Connection String is required, so it’s an integral part of .Net programming, whether it’s ASP.Net or WinForms programming. Of course, here, we’re addressing only ASP.Net programming, and mainly with SQL Server.

Each Connection String has several ‘sections’ in it. The basic form of the Connection String consists of:

ConnectionString=""

Your string can reside in different locations, including a DataSource Control (ASP.Net 2.0), in code, on the fly, and in the Web.Config file. Most likely, if you are using a particular string in multiple locations throughout your website, it will probably be best to store it in the Web.Config file. Then, any time, in your application, you need the connection string, the setting in the Web.Config file is referenced instead of the exact connection string. This way, if the connection string ever changes (and believe me, after years of doing this, I’m here to attest that it most likely WILL change at some time), then you will only need to change it in one place. How this is done, will be addressed, later on in this tutorial,

There are many sections of a connection string which are possible, but there are 3 basic sections which are absolutely required: The ServerThe Database NameThe authentication

The Server can be notated in the Connection String several different ways, however, the most common usages are:

Data Source=YourServerGoesHere
Server=YourServerGoesHere

In the above section, instead of ‘YourServerGoesHere’, you would put the address to the Server itself, in either a domain type of construction (like:MyServer.Com), or an IP address (like: 198.12.1987).

So, at this point, using the Basic form from above, this would look like:

Naturally, the above, as mentioned before, can use ‘Server’ instead of ‘Data Source’

Next comes the Database section. It may be in 2 different forms:

Database=Northwind
Intial Catalog=Northwind

The different sections in the Connection String need to be separated, so in order to do this, we use a semi-colon in between the different sections “;”. The entire connection string, then, will be surrounded by double-quotes

At this point, using the Basic form from above, this would look like:Continues…