现在的位置: 首页 > 综合 > 正文

c# 调用存储过程

2012年01月11日 ⁄ 综合 ⁄ 共 1126字 ⁄ 字号 评论关闭

本例调用存储过程的方法为:

设置SqlCommand.Comand为CommandType.StoredProcedure,并使用DataReader呼叫存储过程。

如下边调用Northwind数据库中的“Ten Most Expensive Products”存储过程代码:

 

using System.Data;
using System.Data.SqlClient;

namespace SqlStoredProcedure
{
    
class Program
    {
        
static void Main(string[] args)
        {
            SqlConnection thisConnection 
= new SqlConnection(
            
@"Data Source=scott;Initial Catalog=northwind;Persist Security Info=True;User ID=sa;Password=sa123");
            thisConnection.Open();

            SqlCommand thisCommand = thisConnection.CreateCommand();
            
//命令类型为存储过程
            thisCommand.CommandType = CommandType.StoredProcedure;
            
//存储过程名称
            thisCommand.CommandText = "Ten Most Expensive Products";

            //执行存储过程
            SqlDataReader thisReader = thisCommand.ExecuteReader();

            //显示结果
            while(thisReader.Read())
            {
                Console.WriteLine(
"\t{0}\t{1}", thisReader["TenMostExpensiveProducts"], thisReader["UnitPrice"]);
            }

            thisReader.Close();
            thisConnection.Close();
            Console.ReadLine();
        }
    }

抱歉!评论已关闭.