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是存储过程名 sqlCmd = new SqlCommand("SalesByCategory", sqlConn); //指明执行的是存储过程 sqlCmd.CommandType = CommandType.StoredProcedure; //构造SqlParameter对象 SqlParameter sqlParam = sqlCmd.Parameters.Add("@CategoryName", SqlDbType.NVarChar, 15); // sqlParam.Value = "Beverages"; //打开数据库 sqlConn.Open(); //执行查询,并将结果集返回给SqlDataReader sqlDR = sqlCmd.ExecuteReader(); Console.WriteLine("{0}\t\t{1}", sqlDR.GetName(0), sqlDR.GetName(1)); //遍历所有的行,直到结束 while (sqlDR.Read()) { Console.WriteLine("{0}\t\t${1}", sqlDR.GetString(0), sqlDR.GetDecimal(1)); } } catch (System.Exception e) { Console.WriteLine(e.Message); } finally { //关闭SqlDataReader对象 sqlDR.Close(); //断开数据库连接 sqlConn.Close(); } } } }