Monday, January 23, 2012

How to Connect Sql Server using web.config file

Hi Everyone who newly to MS SQL Server. Here I have described Various Mathods to connect with SQL server to use it various Functionality.

1) Using Web.Config File  in your Visual Studio

As you create your project in Visual Studio you will find web.config file It is a good practice to store the connection string for your application in a config file rather than as a hard coded string in your code. The way to do this differs between .NET 2.0 and .NET 3.5 (and above). This article cover booth.

Connection string in .NET 2.0 config file
In the appSettings location, add a key named whatever you like to reference your connection string to.
<add key="myConnectionString" value="server=localhost;database=myDb;uid=myUser;password=myPass;" />
To read the connection string from code, use the ConfigurationSettings class.
string connStr = ConfigurationSettings.AppSettings("myConnectionString");
Now you have the connection string loaded from web.config into your string variable in code.

Connection string in .NET 3.5 (and above) config file
Do not use appsettings in web.config. Instead use the connectionStrings section in web.config.
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
To read the connection string into your code, use the ConfigurationSettings class.
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

No comments:

Post a Comment