1. 填充DataSet
//建立连接
SqlConnection sqlConn=new SqlConnection(@"server=(local);Integrated Security=true;Database=Northwind;");
sqlConn.Open();    //打开连接

string SQL="select * from Employees ";
SqlDataAdapter da=new SqlDataAdapter(SQL,sqlConn);    //定义adapter

    DataSet ds=new DataSet();
    da.Fill(ds,"Employees"); 

    DataTable dt=ds.Tables["Employees"];


2。筛选与排序

DataTableCollection dtc=ds.Tables; //将ds中所有Table给dtc实例,内部为按顺序填充

    //使用一个过滤器
    string fl="Country='Germany'";
    string str="CompanyName Asc";
    //输出dtc中的第一个表,即Customers表
    foreach(DataRow dRow in dtc[0].Select(fl,str))
    {
     Console.WriteLine("{0}\t{1}",dRow["CompanyName"].ToString().PadRight(25),dRow["ContactName"]);
    }

    Console.WriteLine("---------");

    //输出dtc中的第二个表
    foreach(DataRow dRow in dtc[1].Rows)
    {
     Console.WriteLine("{0}\t{1}",dRow["ProductName"].ToString().PadRight(25),dRow["UnitPrice"]);
    }

3。使用DATAVIEW

DataTable dt=ds.Tables["Customers"];
    //创建dataview实例---(数据表源,筛选条件,排序字段,包含的行的类型(所有))
    DataView myView=new DataView(dt,"Country='Germany'","Country",DataViewRowState.CurrentRows);

    //遍历dataview中的对象
    foreach(DataRowView myDrv in myView)
    {
     for(int i=0;i<myView.Table.Columns.Count;i++)
     Console.WriteLine(myDrv[i]+"\t");
     Console.WriteLine();
    }

4。修改DATASET中的数据(使用COMMANDBUILDER),    将变化返回数据库中
//修改单独一行
    dt.Rows[0]["FirstName"]="Gareth";
    
    //增加一行
    DataRow newRow=dt.NewRow();
    //newRow["EmployeeID"]=10;ID为自动生成
    newRow["FirstName"]="Aaron";
    newRow["LastName"]="Gu";
    newRow["City"]="NanKing";
    newRow["Country"]="China";
    dt.Rows.Add(newRow);

    //显示修改后dt内的结果(未返回数据库中)
    foreach(DataRow myRow in dt.Rows)
    {
     Console.WriteLine("{0}{1}\t{2}",myRow["FirstName"],myRow["LastName],myRow["City"]);
    }

    //使用CommandBuilder的条件:有主键;设置了dataadapter的selectCommand属性。
    SqlCommandBuilder sqlCb=new SqlCommandBuilder(da);
    da.Update(ds,"Employees");

5.把DATASET写/读到XML中
    ds.WriteXml(@"c:\Products.xml");
    ds.ReadXml(@"c:\Products.xml");

posted on 2006-03-22 13:31  locksley  阅读(198)  评论(0)    收藏  举报