Saturday, September 8, 2012

Database Connection in web.config

Let me show you how to give connection string in web.config and then use it in your .aspx pages or other classes.

Below is the webconfig where I have defined the connection string...





Above you can see that connectionstring has four things -:

1. Data Source - This is the name of the server where the application database will be hosted. I have written it as localhost because my database is on my local machine. Instead of writing localhost you ca simply write dot(.). That will also work fine.

2. Initial Catalog - This is the name of your database.

3. User Id - As the name suggests it is the username.

4. Password - As the name suggests it is the password.   

You give the connectionstring a name. You will refer to the connection string in your application by using this name. For example in my application I have named it as "Practice_ConnectionString".

And lastly you have the providername i.e. System.Data.SqlClient. This is important as this tells the application that it has to refer to the ms sql server.

Now we are done with adding the connectionstring in web.config. But hey, how to use it in the application...

Relax...I will show you how....Goto Default.aspx.cs in your application

Here you will include these three statements before continuing....

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



Here above you will see that I have created a variable conStr  which will hold the reference to the connectionstring defined in the web.config.

After that I have initialized a new instance of SqlConnection class con  and passed the conStr  to it...

So here we are done with connecting application to database with connection string defined in web.config....

Happy Connecting!!!!









No comments:

Post a Comment