how to connect database in c#
  • how to connect msql express 2005 in vs 2008 i want to fetch data from my database.Who make in microsoft SQL server management studio express.
  • 2 Comments sorted by
  • Vote Up0Vote Down WaqasWaqas
    172.00 Karma Accepted Answer
    Hi first you have to use using System.Data.SqlClient; at top and code is also below and attach with database in attachment.




    //make object of SqlConnection
    SqlConnection con = new SqlConnection();

    //assign connection string to connection
    con.ConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=dbPostSample;Integrated Security=True";

    //make object of SqlCommand for define query
    SqlCommand cmd = new SqlCommand();

    //assign query and connection to sqlcommand
    cmd.Connection = con;
    cmd.CommandText = "select Message from tblMessage";

    //make object of datareader
    SqlDataReader dr;
    //open connection
    con.Open();

    //execute query it will return your query result as SqlDataReader
    //who will store in dr object
    dr = cmd.ExecuteReader();

    //now read data from dr object
    dr.Read();

    //check query have returen any data or not?
    if (dr.HasRows)
    {
    //display data in message box
    //"Message" is my column name you can also use column index query vise
    MessageBox.Show(dr["Message"].ToString(), "www.codingresolved.com");
    }
    //close datareader and sqlconnection
    dr.Close();
    con.Close();
    DbSamplePost.zip
    37K
  • Thanks waqas very useful code.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, or you want to Ask a new Question, Please Login or Create a new Account by Clicking below

Login with Facebook

Tagged

Popular Posts of the Week

Optimum Creative