如何使用DataSet修改数据库?
如何使用DataSet修改数据库?
//数据库连接
SqlConnection con = new SqlConnection("server=.;database=Test;uid=sa;pwd=;");
SqlConnection con = new SqlConnection("server=.;database=Test;uid=sa;pwd=;");
//创建一个SqlDataAdapter
SqlDataAdapter sda = new SqlDataAdapter("Select * From Guest", con);
SqlDataAdapter sda = new SqlDataAdapter("Select * From Guest", con);
//创建一个DataSet,并从Authors获取数据
DataSet ds = new DataSet();
sda.FillSchema(ds,SchemaType.Source, "Authors");
sda.Fill(ds,"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);
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();
dr = dt.Rows.Find("Steven");
dr.BeginEdit();
dr["Phone"] = "987654321";
dr.EndEdit();
//更新数据库中的数据
//插入和编辑后,更新需要创建一个SqlCommandBuilder
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
sda.Update(ds, "Authors");
//插入和编辑后,更新需要创建一个SqlCommandBuilder
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
sda.Update(ds, "Authors");
//删除代码
drCurrent = tblAuthors.Rows.Find("993-21-3427");
drCurrent.Delete();
drCurrent = tblAuthors.Rows.Find("993-21-3427");
drCurrent.Delete();
//更新数据库中的数据
//删除操作后,更新不需要创建SqlCommandBuilder
daAuthors.Update(dsPubs, "Authors");
//删除操作后,更新不需要创建SqlCommandBuilder
daAuthors.Update(dsPubs, "Authors");