用DataSet修改数据库

//数据库连接
SqlConnection con = new SqlConnection("server=.;database=Test;uid=sa;pwd=;");
//创建一个SqlDataAdapter
SqlDataAdapter sda = new SqlDataAdapter("Select * From Guest", con);
//创建一个DataSet,并从Authors获取数据
DataSet ds = new DataSet();
sda.FillSchema(ds,SchemaType.Source, "Authors");
sda.Fill(ds,"Authors");
 
//添加代码
DataTable dt = ds.Tables["Authors"];
DataRow dr = dt.NewRow();
dr["Name"] = "Steven";
dr["Phone"] = "123456789";
dt.Rows.Add(dr);
 
//编辑代码
dr = dt.Rows.Find("Steven");
dr.BeginEdit();
dr["Phone"] = "987654321";
dr.EndEdit();
 
//更新数据库中的数据
//插入和编辑后,更新需要创建一个SqlCommandBuilder
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
sda.Update(ds, "Authors");
 
//删除代码
drCurrent = tblAuthors.Rows.Find("993-21-3427");
drCurrent.Delete();
 
//更新数据库中的数据
//删除操作后,更新不需要创建SqlCommandBuilder
daAuthors.Update(dsPubs, "Authors");
 

例如:   

            DataSet ds2 = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter("select * from group where groupid=4", @"Data Source=aaa;Initial Catalog=aaa;user id=sa;password=");
            da.Fill(ds2);
            ds2.Tables[0].Rows[0]["groupname"] = "aaaaaaaa";
            SqlCommandBuilder scb = new SqlCommandBuilder(da);
            da.Update(ds2);

posted @ 2008-08-14 14:11  s80895304  阅读(810)  评论(0编辑  收藏  举报