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