DataSet对象
DataSet对象封装在命名空间"System.Data"中。DataSet中可以包含任意数量的DataTable,且每个DataTable对应一个数据库中的数据表和视图。通过DataAdapter对象的Fill方法,将表内容填充到DataSet对象中,而且可以填充多个表,利用别名来区分。
DataSet对象使用XML格式来存储数据,DataSet可以脱离数据源。
DataSet对象使用XML格式来存储数据,DataSet可以脱离数据源。
protected void Page_Load(object sender, EventArgs e)
{
DataSet myds = new DataSet();
DataTable mydt = new DataTable("Squares");
DataRow mydr;
mydt.Columns.Add(new DataColumn("数字", typeof(Int32)));
mydt.Columns.Add(new DataColumn("平方", typeof(Int32)));
for (int i = 0; i < 10; i++)
{
mydr = mydt.NewRow();
mydr[0] = i;
mydr[1] = i * i;
mydt.Rows.Add(mydr);
}
myds.Tables.Add(mydt);
dg1.DataSource = myds.Tables["Squares"].DefaultView;
dg1.DataBind();
}
如果DataSet对象是从数据源读取的数据,可以对DataSet对象进行添加、删除和修改等操作。{
DataSet myds = new DataSet();
DataTable mydt = new DataTable("Squares");
DataRow mydr;
mydt.Columns.Add(new DataColumn("数字", typeof(Int32)));
mydt.Columns.Add(new DataColumn("平方", typeof(Int32)));
for (int i = 0; i < 10; i++)
{
mydr = mydt.NewRow();
mydr[0] = i;
mydr[1] = i * i;
mydt.Rows.Add(mydr);
}
myds.Tables.Add(mydt);
dg1.DataSource = myds.Tables["Squares"].DefaultView;
dg1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("person.mdb");
conn.Open();
string sql = "select * from grade";
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "grade");
DataTable dt = ds.Tables["grade"];
DataRow row = dt.NewRow();
row["学号"] = 14;
row["性别"] = "男";
row["姓名"] = "小齐";
row["语文"] = 78;
row["数学"] = 98;
row["英语"] = 91;
dt.Rows.Add(row);
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
da.Update(ds, "grade");
dg.DataSource = ds.Tables["grade"].DefaultView;
dg.DataBind();
conn.Close();
}
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("person.mdb");
conn.Open();
string sql = "select * from grade";
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "grade");
DataTable dt = ds.Tables["grade"];
DataRow row = dt.NewRow();
row["学号"] = 14;
row["性别"] = "男";
row["姓名"] = "小齐";
row["语文"] = 78;
row["数学"] = 98;
row["英语"] = 91;
dt.Rows.Add(row);
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
da.Update(ds, "grade");
dg.DataSource = ds.Tables["grade"].DefaultView;
dg.DataBind();
conn.Close();
}