用SqlDataReader返回多個結果集

 1 using System;
 2 using System.Data;
 3 using System.Data.SqlClient;
 4 
 5 namespace Northwind
 6 {
 7 class Program
 8 {
 9 static void Main(string[] args)
10 {
11 SqlConnection sqlConn = null;
12 SqlCommand sqlCmd = null;
13 SqlDataReader sqlDR = null;
14 try
15 {
16 //建立鏈接對象,使用集成安全方式鏈接,更安全
17 sqlConn = new SqlConnection(@"data source=localhost;
18 Integrated Security=SSPI;Initial Catalog=northwind");
19 //建立命令對象,參數1是存儲過程名
20 string strSql = @"select categoryid, categoryname from categories;"
21 + @"select employeeId, lastname from employees";
22 sqlCmd = new SqlCommand(strSql, sqlConn);
23 
24 //打開數據庫
25 sqlConn.Open();
26 //執行查詢,並將結果集返回給SqlDataReader
27 sqlDR = sqlCmd.ExecuteReader();
28 
29 //遍歷全部的行,直到結束
30 do 
31 {
32 Console.WriteLine(@"-------------------------------");
33 Console.WriteLine("{0, -15}{1,-15}", sqlDR.GetName(0),
34 sqlDR.GetName(1));
35 Console.WriteLine(@"-------------------------------");
36 while (sqlDR.Read())
37 {
38 Console.WriteLine("{0, -15}${1,-15}", sqlDR.GetInt32(0),
39 sqlDR.GetString(1));
40 }
41 Console.WriteLine();
42 
43 } while (sqlDR.NextResult());
44 
45 }
46 catch (System.Exception e)
47 {
48 Console.WriteLine(e.Message);
49 }
50 finally
51 {
52 //關閉SqlDataReader對象
53 sqlDR.Close();
54 //斷開數據庫鏈接
55 sqlConn.Close();
56 }
57 
58 }
59 }
60 }
相關文章
相關標籤/搜索