DateSet中访问多个表

SqlConnection thisConnection = new SqlConnection(@"Server = ./sqlexpress;Integrated Security = true;" + "Database = northwind");
            SqlDataAdapter thisAdapter = new SqlDataAdapter("SELECT CustomerID,CompanyName FROM Customers", thisConnection);//此处可以省略 但是为了整体看上去层次明显 保留此Apapter
            SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);
            DataSet thisDataSet = new DataSet();

            SqlDataAdapter CustAdapter = new SqlDataAdapter("SELECT * FROM Customers", thisConnection);
            SqlDataAdapter OrderAdapter = new SqlDataAdapter("SELECT * FROM Orders", thisConnection);
           CustAdapter.Fill(thisDataSet,"Customers");
            OrderAdapter.Fill(thisDataSet,"Orders");
            DataRelation thisRelation = thisDataSet.Relations.Add("CustOrder",
                thisDataSet.Tables["Customers"].Columns["CustomerID"],
                thisDataSet.Tables["Orders"].Columns["CustomerID"]);//

            foreach (DataRow custRow in thisDataSet.Tables["Customers"].Rows)
            {
                Console.WriteLine(custRow["CustomerID"] +"/t"+ custRow["CompanyName"]);
                foreach (DataRow orderRow in custRow.GetChildRows(thisRelation))
                {
                    Console.WriteLine(orderRow["OrderID"]);
                }
            }

            thisConnection.Close();

上述例子是两表之间的访问,如果现在有四张表1 2 3 4,应该写成

            DataRelation thisRelation = thisDataSet.Relations.Add("CustOrder1",
                thisDataSet.Tables["1"].Columns["CustomerID"],
                thisDataSet.Tables["2"].Columns["CustomerID"]);//

            DataRelation thisRelation = thisDataSet.Relations.Add("CustOrder2",
                thisDataSet.Tables["2"].Columns["CustomerID"],
                thisDataSet.Tables["3"].Columns["CustomerID"]);//

            DataRelation thisRelation = thisDataSet.Relations.Add("CustOrder3",
                thisDataSet.Tables["3"].Columns["CustomerID"],
                thisDataSet.Tables["4"].Columns["CustomerID"]);//

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值