website-database connectivity using web.config
Today, we will learn database connectivity using web.config <connectionStrings> property.
The main advantage of using connection string in web.config are:
- Security– Web.config file is the configuration file which stores all the server setting required for the web application. And IIS server never allows to browse or view web.config file through browser. So it is very secure.
- Usability– It is very bad habit and waste of time to use again and again connection string to connect the sql server. And use of inline connection string is also increases the line of code which indirectly increase the server load.
Here is the code of web.config file:
<add name=”conn” connectionString=”Data Source=.\sqlexpress;Initial Catalog=mydatabase;Integrated Security=True”/>
And in the c# code we have to use the following code:
SqlConnection Con=new SqlConnection(ConfigurationManager.ConnectionStrings[“conn”].ConnectionString);
In the web.config file in the <connectionStrings> property there is a property named <add> which holds the connection string. and a Name which will be used in the class file.
ConfigurationManager is used to get the properties of web.config file, and here we are using ConnectionStrings
property of web.config file.
See the example ConfigurationManager.ConnectionStrings[“conn”].ConnectionString
How useful was this post?
Click on a star to rate it!
Average rating / 5. Vote count: