本帖最后由 傅涌钦 于 2011-12-31 04:34 编辑
无奈!天都快亮了!!举两个表的,再多的应该是一个模式了:
App.config:- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <connectionStrings >
- <add name="connstr" connectionString="Server=(local);Integrated Security=SSPI;uid=user id;pwd=password;Database=mydb"/>
- </connectionStrings>
- </configuration>
复制代码 C# Code;- static void Main(string[] args)
- {
- //ExcuteDataReader()多表查询
- //String connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
- //using (SqlConnection conn = new SqlConnection(connstr))
- //{
- // conn.Open();
- // using (SqlCommand cmd = conn.CreateCommand())
- // {
- // cmd.CommandText = "select Student.Sno,Sname,Cno,cj from Student,SC where Student.Sno=SC.Sno";
- // SqlDataReader reader = cmd.ExecuteReader();
- // while (reader.Read())
- // {
- // Console.WriteLine("学号:{0} \t 名字:{1}\t 课程号:{2}\t 成绩:{3}\t ", reader[0], reader[1], reader[2], reader[3]);
- // }
- // }
- //}
- //DataSet多表查询
- String connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
- using (SqlConnection conn = new SqlConnection(connstr))
- {
- conn.Open();
- using (SqlCommand cmd = conn.CreateCommand())
- {
- //cmd.CommandText = "select Student.Sno,Sname,Cno,cj from Student,SC where Student.Sno=SC.Sno";
- }
- DataSet ds = new DataSet();
- //填充数据
- SqlDataAdapter adatapter = new SqlDataAdapter("select * from SC", conn);
- adatapter.Fill(ds, "SC");
- SqlDataAdapter adatapter1 = new SqlDataAdapter("select * from Student", conn);
- adatapter1.Fill(ds, "Student");
- //创建两表关联
- ds.Relations.Add("SC", ds.Tables["Student"].Columns["Sno"], ds.Tables["SC"].Columns["Sno"]);
- //迭代Student表;
- foreach (DataRow student in ds.Tables["Student"].Rows)
- {
- Console.WriteLine("学号:{0}\t 姓名:{1}\t\n", student["Sno"], student["Sname"]);
- //遍历选课表
- foreach (DataRow sc in ds.Tables["SC"].Rows)
- {
- Console.WriteLine("课程号:{0}\t 成绩:{1}\t", sc["Cno"], sc["cj"]);
- }
- }
- }
- Console.ReadKey();
- }
复制代码 :传说用LINQ 会比较简单,还没学到,不了解,伤感! |