以下是从ASP.NET1.0的例子中的摘抄的代码,通过代码用数据适配器对数据库添加、删除、修改、查询。
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection conn2 = new SqlConnection("data source=(local);database=Northwind;user=sa; password=8888"); //创建连接对象
SqlDataAdapter da2 = new SqlDataAdapter();
//适配器对象的查询命令
SqlCommand cmdSel=new SqlCommand("select RegionID, RegionDescription from Region", conn2); //创建DataAdapter(数据适配器)
da2.SelectCommand = cmdSel;
//适配器对象的更新命令
SqlCommand cmdUpdate = new SqlCommand("update Region set RegionDescription =@RegionDescription where RegionID = @RegionID", conn2);
SqlParameter paramID = new SqlParameter("@RegionID",SqlDbType.Int);
paramID.SourceColumn = "RegionID"; //数据值对应的字段
paramID.SourceVersion = DataRowVersion.Original; //数据值将使用初始版本的数值
cmdUpdate.Parameters.Add("@RegionDescription",SqlDbType.NChar,50,"RegionDescription");
cmdUpdate.Parameters.Add(paramID);
da2.UpdateCommand = cmdUpdate; //
//适配器对象的添加命令
SqlCommand cmdInsert = new SqlCommand("insert into Region(RegionDescription) values (@RegionDescription)", conn2);
cmdInsert.Parameters.Add("@RegionID", SqlDbType.Int, 4, "RegionID");
cmdInsert.Parameters.Add("@RegionDescription", SqlDbType.NChar, 50, "RegionDescription");
da2.InsertCommand = cmdInsert;
//适配器对象的删除命令
SqlCommand cmdDel = new SqlCommand("delete * from Region where RegionID=@RegionID", conn2);
SqlParameter paramDelID = new SqlParameter("@RegionID", SqlDbType.Int);
paramDelID.SourceColumn = "RegionID";
paramDelID.SourceVersion = DataRowVersion.Original;
cmdDel.Parameters.Add(paramDelID);
da2.DeleteCommand = cmdDel;
DataSet ds2 = new DataSet(); //创建DataSet(数据集)
da2.Fill(ds2,"Region"); //使用数据适配器填充数据集
GridView1.DataSource = ds2; //显示,绑定
//GridView1.DataMember = "mybaobiao";
GridView1.DataBind();
//添加数据
DataRow addrow = ds2.Tables[0].NewRow();
addrow[1] = "碧海湾8";
ds2.Tables[0].Rows.Add(addrow);
da2.Update(ds2, "Region");
//修改数据
DataRow editrow = ds2.Tables["Region"].Rows[0];
//editrow.BeginEdit();
editrow["RegionDescription"] = "北京9北京9北京9";
//editrow.EndEdit();
GridView1.DataSource = ds2; //显示,绑定
GridView1.DataBind();
da2.Update(ds2, "Region");
//删除数据
DataRow editrow1 = ds2.Tables["Region"].Rows[3];
editrow1.Delete();
GridView1.DataSource = ds2; //显示,绑定
GridView1.DataBind();
//da2.Update(ds2,"Region")
}