Step by step process of getting connection string from web.config

Getting Connection string from web.config
In web.config file you find tag like this

<connectionStrings/>

We have to write a connection in connectionstring tag so that we can use in our application.

Steps are

1.replace <connectionStrings/> by

<connectionStrings>
</connectionStrings>

2.add connection string to this tag
Sql Authentication Connection,you have the user name and passwords of ur database

<add name="ConnectionStringName" connectionString="Data Source=.\Sqlexpress;Initial Catalog=databasename;User ID=databaseuserid;Password=databasepassword" providerName="System.Data.SqlClient"/>

Windows Authentication Connection default settings of Sqlserver2005

<add name="ConnectionStringName" connectionString="Data Source=.\Sqlexpress;Initial Catalog=databasename;integrated security=SSPI" providerName="System.Data.SqlClient"/>

Just u have to replace User ID=databaseuserid;Password=databasepassword to
integrated security=SSPI that’s all for Sql Authentication to Windows Authentication

It look like this

<connectionStrings>
<add name="ConnectionStringName" connectionString="Data Source=.\Sqlexpress;Initial Catalog=databasename;User ID=databaseuserid;Password=databasepassword" providerName="System.Data.SqlClient"/>
</connectionStrings>

or

<connectionStrings>
<add name="ConnectionStringName" connectionString="Data Source=.\Sqlexpress;Initial Catalog=databasename;integrated security=SSPI" providerName="System.Data.SqlClient"/>
</connectionStrings>

3. Getting Connection from web.config using c#

Add fallowing Namespace to your application

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

Code for getting connection

SqlConnection sqlConn = null;

String str=
WebConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString();

// Note:Ensure ConnectionStringName is same we mentioned in web.config file that all

sqlConn = new SqlConnection(str);
sqlConn.Open();

// do operation

sqlConn.Close();

Enjoy this coding…

1 comment:

Krishna said...

Thanks a lot... It was very helpful...