To connect a data base in asp.net we can use two methods or ways. First one can be the page another can be assigning in web config file and the access the connection any where in the solution. But before starting please notice, that you must have desired namespace included. In this article we are using sql server so the two important namespace which we must include are: system.data and system.data.sql Client.
After including both the namespace then we start with the basic inline procedure where we directly put the connection on the page. The disadvantage of this that we can only can use this connection in particular page on which it is declared not on each page of the solution then we have to define on each page that’s why the web config method is better. So following is the syntax for this:
SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
Now in web config method, we declare the connection in the following way.
<add name="conn" connectionString="Data Source=SHASHI-6DE5F247\SQLEXPRESS;Initial Catalog=pinfo;Integrated Security=True;User Instance=False" providerName="System.Data.SqlClient"/>
And on each page we can access using following way
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);