对于dataAdapter与dataSet和dataTable的填充,可以分为1对1,1对n,n对n,3种情况。
以SqlDataAdapter为例。
//(1)1对1 SqlDataAdapter da=new SqlDataAdapter("SqlString",SqlConnection); da.fill(dataset,"tableName"); //(2)1对n SqlDataAdapter da=new SqlDataAdapter("SqlString1",SqlConnection); da.fill(dataset1,"tableName1"); //这里重新填充sql语句,填充对象可以使多个dataSet和dataTable。 da=new SqlDataAdapter("SqlString2",SqlConnection); da.fill(dataset2,"tableName2"); //其他的情况类似,可以依次类推到第n张表或数据集。 //(3)n对n SqlDataAdapter da1=new SqlDataAdapter("SqlString1",SqlConnection); da1.fill(dataset1,"tableName1"); //这里重新填充sql语句,填充对象可以使多个dataSet和dataTable。 SqlDataAdapter da2=new SqlDataAdapter("SqlString2",SqlConnection); da2.fill(dataset2,"tableName2");
//数据库查询 DataSet 添加多张DateTable SqlDataAdapter custAdapter = new SqlDataAdapter( "SELECT * FROM dbo.Customers", customerConnection); OleDbDataAdapter ordAdapter = new OleDbDataAdapter( "SELECT * FROM Orders", orderConnection); DataSet customerOrders = new DataSet(); custAdapter.Fill(customerOrders, "Customers"); ordAdapter.Fill(customerOrders, "Orders"); //--以下为应用 DataRelation relation = customerOrders.Relations.Add("CustOrders", customerOrders.Tables["Customers"].Columns["CustomerID"], customerOrders.Tables["Orders"].Columns["CustomerID"]); foreach (DataRow pRow in customerOrders.Tables["Customers"].Rows) { Console.WriteLine(pRow["CustomerID"]); foreach (DataRow cRow in pRow.GetChildRows(relation)) Console.WriteLine(" " + cRow["OrderID"]); } //---------------------------
参考:
1. lllljz的专栏 dataAdapter与dataSet和dataTable的填充
2. https://msdn.microsoft.com/zh-cn/library/bh8kx08z.aspx