Monday, 1 July 2013

Connect Asp Page to Database

As a developer I faced many problem in connecting database but after two days i realized that it is very easy for me. Okay! i will not waste your time so much and now start this tutorial.

1. While connecting SQL Server to your system if it shows error like this 1856 or something else so you should not worry so much about this. You should restart your SQL Server as run as administrator.
and this will solve your problem. But If this is not working then you should search on internet related to your problem.

Make Connection String to your database:

you can do this by two ways.

1. By using ConfigrationManager

2. Directly give the path to your database.

Now first of all see second method.

How to get database source path?

see this picture if your database is connected  this will help you.

At the right corner you will get your data source path.

Do the following steps to get connection:

1. Add namespace  using System.Data.SqlClient;

2. Write connection code in on page load event or in button click event, like this:
      SqlConnection con = new SqlConnection("Data Source=CHHILLAR;Initial Catalog=CarImage;Integrated Security=True");  // you will have to write your own connecting path in bracket

3. Now open the connection by this way
    con.Open();     // here con is the variable as we used it in making connecting string

now after this you will be able to write sql command 

Look at First method now.

1. Add another namespace Configuration like this
   using System.Configuration;
2. SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CarImageConnectionString"].ConnectionString);

here CarImage is my database name from which i will retrieve and insert data.
But one more thing you should do that open your config page and add this configuration there also like this



now you are free to give sql command to your web page.
your comment will be improve my blog so if you face any problem send me through your comment. To know more about this click here at Microsoft official page