SqlDataAdapter Update Method
- SqlDataAdapter is a part of the ADO.NET
Data Provider.
- It uses Fill method to retrieve data from
data source and fill it in DataSet.
- The UpdateCommand of the SqlDataAdapter
Object update the database with the data modifications made on a DataSet
object.
Diagram:
Steps:
- Create a update query string.
- Create a connection object.
- Create a SqlDataAdapter object
accompanying the query string and connection object.
- 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...