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 }