1. 程式人生 > >C#呼叫Sql Server 2008的儲存過程流程

C#呼叫Sql Server 2008的儲存過程流程

前言

最近用到了sql server 2008的儲存過程,特此整理成文

流程步驟

1.獲取連結

SqlConnection myConnection = new SqlConnection(@”server=主機名;uid=賬號;pwd=密碼;database=資料庫名;Trusted_Connection=no”);

2..建立可以執行SQL語句的SqlCommand

SqlCommand MyCommand = new SqlCommand(“儲存過程名“, myConnection); //定義一個數據庫操作指令

##3.指明呼叫的是儲存過程

MyCommand.CommandType = CommandType.StoredProcedure;//設定該語句是讀取儲存過程的

4.設定資料介面卡

SqlDataAdapter SelectAdapter = new SqlDataAdapter();//定義一個數據介面卡
SelectAdapter.SelectCommand = MyCommand;//定義資料介面卡的操作指令

5.執行儲存過程

try{
      myConnection.Open();//開啟資料庫連線
      SelectAdapter.SelectCommand.ExecuteNonQuery();//執行資料庫查詢指令
      myConnection.Close();//關閉資料庫
    }catch (Exception
e) { throw new Exception(e.ToString()); }

6.將結果儲存到DataSet裡

DataSet MyDataSet = new DataSet();//定義一個數據集SelectAdapter.Fill(MyDataSet);//填充資料集

7.解析DataSet中的資料

DataTable dt = MyDataSet.Tables[0];//獲取查詢的結果表(因為只有一個)
列型別 變數別名= (列型別)dt.Rows[0][“列名“];

完整版

SqlConnection myConnection = new
SqlConnection(@"server=`主機名`;uid=`賬號`;pwd=`密碼`;database=`資料庫名`;Trusted_Connection=no"); SqlCommand MyCommand = new SqlCommand("`儲存過程名`", myConnection); //定義一個數據庫操作指令 MyCommand.CommandType = CommandType.StoredProcedure;//設定該語句是讀取儲存過程的 SqlDataAdapter SelectAdapter = new SqlDataAdapter();//定義一個數據介面卡 SelectAdapter.SelectCommand = MyCommand;//定義資料介面卡的操作指令 try{ myConnection.Open();//開啟資料庫連線 SelectAdapter.SelectCommand.ExecuteNonQuery();//執行資料庫查詢指令 myConnection.Close();//關閉資料庫 }catch (Exception e) { throw new Exception(e.ToString()); } DataSet MyDataSet = new DataSet();//定義一個數據集SelectAdapter.Fill(MyDataSet);//填充資料集 DataTable dt = MyDataSet.Tables[0];//獲取查詢的結果表(因為只有一個) `列型別` 變數別名= (`列型別`)dt.Rows[0]["`列名`"];

歡迎交流