Thursday, April 1, 2010

Select, Insert, Update and Delete using SqlDataAdapter

We can do the select, insert, update and delete to dataset by using SqlDataAdapter. See the following code to do that:-

SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=master;uid=sa;pwd=sql;");

SqlDataAdapter adapter = new SqlDataAdapter("select * from Customer", con);

DataSet ds = new DataSet();
//fill the dataset
adapter.Fill(ds, "emp");

//CREATE select command and build with adapter

SqlCommand cmdSelect = new SqlCommand("select * from Customer", con);
adapter.SelectCommand = cmdSelect;

//CREATE the insert command and build with adapter

SqlCommand cmdInsert = new SqlCommand("insert into emp (cusotmerName, location) values(@customerName, @location)", con);
cmdInsert.Parameters.AddWithValue("@customerName", "SENTHILNATHAN");
cmdInsert.Parameters.AddWithValue("@location", "CHENNAI");
adapter.InsertCommand = cmdInsert;

//Create update command and build with adapter

SqlCommand cmdUpdate = new SqlCommand("update emp set cusotmerName=@customerName, location=@location where CustomerNo=@CustomerNo", con);
cmdUpdate.Parameters.AddWithValue("@customerName", "SENTHILNATHAN");
cmdUpdate.Parameters.AddWithValue("@location", "CHENNAI");
cmdUpdate.Parameters.AddWithValue("@CustomerNo", "100");
adapter.UpdateCommand = cmdUpdate;

//build delete command and build with adapter

SqlCommand cmdDelete = new SqlCommand("delete from emp where CustomerNo=@CustomerNo", con);
cmdDelete.Parameters.AddWithValue("@CustomerNo", 104);
adapter.DeleteCommand = cmdDelete;

//now update the data adapter with dataset.

adapter.Update(ds, "emp");




-----------------------------------------------------------------------------