SqlDataAdapter Update Method


SqlDataAdapter Update Method

  1. SqlDataAdapter is a part of the ADO.NET Data Provider.
  2. It uses Fill method to retrieve data from data source and fill it in DataSet.
  3. The UpdateCommand of the SqlDataAdapter Object update the database with the data modifications made on a DataSet object.

Diagram:

sql.gif

Steps:

  1. Create a update query string.
  2. Create a connection object.
  3. Create a SqlDataAdapter object accompanying the query string and connection object.
  4. Use the Update command of SqlDataAdapter object to execute the update query.

Example:

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("connetionString");
            string qry = "SELECT * FROM SOMETABLE";
            SqlDataAdapter da = new SqlDataAdapter(qry,con);
           
            //Fill the DataSet
            DataSet ds = new DataSet();
            da.Fill(ds, "SomeTable");
           
//Update a row in DataSet Table
            DataTable dt = ds.Tables["SomeTable"];
            dt.Rows[0]["SomeColumn"] = "xyz";

            string sql = "update sometable set somecolumn = 10 where ...";
            SqlDataAdapter adapter = new SqlDataAdapter();           
            try
            {
                connection.Open();
                SqlCommand cmd = new SqlCommand(sql, con);
               
//select the update command
                adapter.UpdateCommand=cmd;
               
//update the data source
                adapter.Update(ds,"SomeTable");
                MessageBox.Show ("DataBase updated !! ");
            }
            catch (Exception ex)
            {
                connection.Close();
            }
        }



Happy Learning...

Up Next
    Ebook Download
    View all
    Learn
    View all