4.)新建一个控制台的应用程序 代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { GetSalesByCategory("server=.;uid=sa;pwd=123456;database=Northwind", "Produce");//在这里就默认设置了 参数@CategoryName参数的值为 Produce } static void GetSalesByCategory(string connectionString,string categoryName) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "SalesByCategory"; //CommandType 属性设置为 StoredProcedure 时,CommandText 属性应设置为存储过程的名称 command.CommandType = CommandType.StoredProcedure; //设置执行类型为存储过程 SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@CategoryName";//指定存储过程中的那个参数 parameter.SqlDbType = SqlDbType.NVarChar;//指定数据类型 parameter.Direction = ParameterDirection.Input;//指定参数为输入 parameter.Value = categoryName; command.Parameters.Add(parameter); connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows)//判断是否有数据行 { while (reader.Read()) { Console.WriteLine("{0}: {1:C}", reader[0], reader[1]); } } else { Console.WriteLine("No rows found."); } reader.Close();//记得关闭 Console.ReadLine(); } } } }
前面简单提到了 Connection 、DataReader、Comand以及参数和存储过程的用法,现在更加深入的学习。
1.DataReader的用法:
DataReader 从数据库中检索只读、只进的数据流。查询结果在查询执行时返回,在并存储在客户端的网络缓冲区中,直到您使用 DataReader 的 Read 方法对它们发出请求。 使用 DataReader 可以提高应用程序的性能,原因是它只要数据可用就立即检索数据,并且(默认情况下)一次只在内存中存储一行,减少了系统开销。