using System;
using System.Data;
using System.Data.SqlClient;
namespace Northwind
{
class Program
{
static void Main(string[] args)
{
SqlConnection sqlConn = null;
SqlCommand sqlCmd = null;
SqlDataReader sqlDR = null;
try
{
//创建连接对象,使用集成安全方式连接,更安全
sqlConn = new SqlConnection(@"data source=localhost;
Integrated Security=SSPI;Initial Catalog=northwind");
//创建命令对象,参数1是存储过程名
string strSql = @"select categoryid, categoryname from categories;"
+ @"select employeeId, lastname from employees";
sqlCmd = new SqlCommand(strSql, sqlConn);
//打开数据库
sqlConn.Open();
//执行查询,并将结果集返回给SqlDataReader
sqlDR = sqlCmd.ExecuteReader();
//遍历所有的行,直到结束
do
{
Console.WriteLine(@"-------------------------------");
Console.WriteLine("{0, -15}{1,-15}", sqlDR.GetName(0),
sqlDR.GetName(1));
Console.WriteLine(@"-------------------------------");
while (sqlDR.Read())
{
Console.WriteLine("{0, -15}${1,-15}", sqlDR.GetInt32(0),
sqlDR.GetString(1));
}
Console.WriteLine();
} while (sqlDR.NextResult());
}
catch (System.Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
//关闭SqlDataReader对象
sqlDR.Close();
//断开数据库连接
sqlConn.Close();
}
}
}
}
------------------------------- categoryid categoryname ------------------------------- 1 $Beverages 2 $Condiments 3 $Confections 4 $Dairy Products 5 $Grains/Cereals 6 $Meat/Poultry 7 $Produce 8 $Seafood
------------------------------- employeeId lastname ------------------------------- 5 $Buchanan 8 $Callahan 1 $Davolio 9 $Dodsworth 2 $Fuller 7 $King 3 $Leverling 4 $Peacock 6 $Suyama
请按任意键继续. . .