DataRelation用法,以学生-课程数据库为例

View Code
 1 using System;
 2 
 3 using System.Collections.Generic;
 4 
 5 using System.Linq;
 6 
 7 using System.Text;
 8 
 9 using System.Data;
10 
11 using System.Data.SqlClient;
12 
13  
14 
15 namespace 学生_课程
16 
17 {
18 
19     class Program
20 
21     {
22 
23         static void Main(string[] args)
24 
25         {
26 
27             SqlConnection thisConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\character.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
28 
29             thisConnection.Open();
30 
31             SqlDataAdapter thisAdapter = new SqlDataAdapter("SELECT Sno,Sname FROM Student",thisConnection);
32 
33             SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);
34 
35             DataSet thisDataSet = new DataSet();
36 
37             SqlDataAdapter stuAdapter = new SqlDataAdapter("SELECT * FROM Student", thisConnection);
38 
39             SqlDataAdapter scAdapter = new SqlDataAdapter("SELECT * FROM SC",thisConnection);
40 
41             stuAdapter.Fill(thisDataSet,"Student");
42 
43             scAdapter.Fill(thisDataSet, "SC");
44 
45             DataRelation stuScRelation = thisDataSet.Relations.Add("stuSc",thisDataSet.Tables["Student"].Columns["Sno"],thisDataSet.Tables["SC"].Columns["Sno"]);//后两处相当于主键和外键
46 
47             foreach (DataRow stuRow in thisDataSet.Tables["Student"].Rows)
48 
49             {
50 
51                 Console.WriteLine("Student Number: "+stuRow["Sno"]+"Student Name: "+stuRow["Sname"]);
52 
53                 foreach (DataRow scRow in stuRow.GetChildRows(stuScRelation))//调用DataRow的GetChildRows()方法对其进行初始化。将DataRelation对象传递给 GetChildRows().该方法返回DataRowCollection。其中包含上一级在此表中的相关行.
54 
55                 {
56 
57                     Console.WriteLine("Grade: "+scRow["Grade"]);
58 
59                 }
60 
61             }
62 
63             thisConnection.Close();
64 
65             Console.ReadKey();
66 
67         }
68 
69     }
70 
71 }
72 
73  

转载于:https://www.cnblogs.com/stansonwilliam/archive/2012/10/26/2740485.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值