How to write Connection String in Web.config file

If you are fond of designing application in ASP.Net….??? You might have seen people (mainly beginners) writing connection string on each and every page of their application.

My question:   Is this approach feasible?

Obviously no…!
Think of a scenario, Your application has 100 web pages and you wrote connection string on every single web page of your application, and now time comes when you need to upload it over the server.

As you might be aware of the fact that database at server have their own connection string in-fact every system does. Now main problem you’ll face will be replacing the connection string in your application with one that on server. What will you do? Modify all 100 web pages?

Obviously no…!

Then what if you write connection string at one place and use it on all web pages of your application ( no matter its 100, 1000 or so on..)

Is this a feasible approach??  Obviously Yes, it not only saves your time, but do optimize your application.

 

Now in this, we’ll write our connection string in Web.config file.

Lets see the code and will explain later in this post.

Web.config File

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>

  <!--CONNECTION STRING STARTS-->
    <connectionStrings>
    <add name="myconnectionstring" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|datadirectory|\Database.mdf;Integrated Security=True"
      providerName="System.Data.SqlClient" />
     </connectionStrings>
  <!--CONNECTION STRING ENDS-->

  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
</configuration>

Code Explanation:

I’m assuming that you all know how to find connection string.

The above code is of your Web.config file, as you see under the configuration tag, I have taken a tag connectionString

<!--CONNECTION STRING STARTS-->
    <connectionStrings>
    <add name="myconnectionstring" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|datadirectory|\Database.mdf;Integrated Security=True"
      providerName="System.Data.SqlClient" />
     </connectionStrings>
  <!--CONNECTION STRING ENDS-->

The tag connectionString, under which you will write your connection string. Theirs tag naming “add” with attributes:

  • name- In this you’ll mention the connection string name in order to identify it.
  • providerName- In this we will mention “System.Data.SqlClient”.
  • connectionString- In this we will write our connection string.

On the basis of name we’ll access the connection string on the web pages of our ASP.Net application.



JavaScript, ASP.Net & PHP Web Developer. Connect with me on Facebook and Twitter.

Share This Post

Related Articles

Powered by Paras Babbar · Designed by Paras Babbar