NET用使用預存程序擷取輸出參數的程式碼範例!

來源:互聯網
上載者:User

http://niunan.javaeye.com/category/42319

在網上也找到許多關於.NET中使用預存程序擷取輸出參數的代碼,但怎麼看怎麼都是記不住,還是自己親自實踐一遍後再記錄下來,這樣才能記得住,必竟自己做過的東西是比較難忘記的!!!
    步驟如下:
    ①建立資料庫logintest,在資料庫中建立表User.

     向建立的表中添加幾條測試資料.
    ②在資料庫中建立預存程序:

Sql代碼
  1. USE [logintest]   
  2. GO   
  3. -- =============================================   
  4. -- Author:      牛腩   
  5. -- Create date: 2008-10-21 14:01   
  6. -- Description: 通過傳入的uid擷取使用者姓名   
  7. -- =============================================   
  8. SET ANSI_NULLS ON  
  9. GO   
  10. SET QUOTED_IDENTIFIER ON  
  11. GO   
  12. CREATE PROCEDURE [dbo].[GetUNameById]   
  13. @uid int,   
  14. @name varchar(50) output  
  15. AS  
  16. BEGIN  
  17.     select @name=uname from [User] where uid=@uid   
  18. END  
USE [logintest]GO-- =============================================-- Author:牛腩-- Create date: 2008-10-21 14:01-- Description:通過傳入的uid擷取使用者姓名-- =============================================SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE PROCEDURE [dbo].[GetUNameById]@uid int,@name varchar(50) outputASBEGINselect @name=uname from [User] where uid=@uidEND

    ③在VS中建立一個測試頁面ProcTest.aspx,在ProcTest.aspx.cs中匯入命名空間 C#代碼

  1. using System.Data;   
  2. using System.Data.SqlClient;  
using System.Data;using System.Data.SqlClient;

    ④在Page_Load方法裡寫入如下代碼: C#代碼

  1. // 建立連接字串,在正式項目中可放在web.config中   
  2.        string connStr = "server=niunan\\sqlexpress;uid=sa;pwd=123456;database=logintest";   
  3.        // 串連資料庫   
  4.        SqlConnection conn = new SqlConnection(connStr);   
  5.   
  6.        try  
  7.        {   
  8.            // 開啟資料庫連接   
  9.            conn.Open();   
  10.            // 建立用於執行資料庫操作的命令對象, GetUNameById為預存程序名稱   
  11.            SqlCommand cmd = new SqlCommand("GetUNameById", conn);   
  12.            // 設定執行命令的方式為預存程序   
  13.            cmd.CommandType = CommandType.StoredProcedure;   
  14.   
  15.            // 向命令對象添加預存程序所需要的參數   
  16.            cmd.Parameters.Add("@uid", SqlDbType.Int);   
  17.            // 設定要傳入到預存程序的參數值   
  18.            cmd.Parameters["@uid"].Value = 2;   
  19.   
  20.            // 添加預存程序中的輸出參數,如果是字元型的必須定義長度   
  21.            cmd.Parameters.Add("@name", SqlDbType.VarChar, 50);   
  22.            // 設定參數為output輸出參數   
  23.            cmd.Parameters["@name"].Direction = ParameterDirection.Output;   
  24.   
  25.            // 執行預存程序   
  26.            cmd.ExecuteReader();   
  27.   
  28.            // 擷取執行預存程序後的輸出參數   
  29.            string name = cmd.Parameters["@name"].Value.ToString();   
  30.   
  31.            Response.Write(name);   
  32.        }   
  33.        catch (Exception ex)   
  34.        {   
  35.            Response.Write(ex.Message);   
  36.            if (conn.State == ConnectionState.Open)   
  37.            {   
  38.                conn.Close();   
  39.            }   
  40.        }   
  41.        finally  
  42.        {   
  43.            if (conn.State == ConnectionState.Open)   
  44.            {   
  45.                conn.Close();   
  46.            }   
  47.        }   
 // 建立連接字串,在正式項目中可放在web.config中        string connStr = "server=niunan\\sqlexpress;uid=sa;pwd=123456;database=logintest";        // 串連資料庫        SqlConnection conn = new SqlConnection(connStr);        try        {            // 開啟資料庫連接            conn.Open();            // 建立用於執行資料庫操作的命令對象, GetUNameById為預存程序名稱            SqlCommand cmd = new SqlCommand("GetUNameById", conn);            // 設定執行命令的方式為預存程序            cmd.CommandType = CommandType.StoredProcedure;            // 向命令對象添加預存程序所需要的參數            cmd.Parameters.Add("@uid", SqlDbType.Int);            // 設定要傳入到預存程序的參數值            cmd.Parameters["@uid"].Value = 2;            // 添加預存程序中的輸出參數,如果是字元型的必須定義長度            cmd.Parameters.Add("@name", SqlDbType.VarChar, 50);            // 設定參數為output輸出參數            cmd.Parameters["@name"].Direction = ParameterDirection.Output;            // 執行預存程序            cmd.ExecuteReader();            // 擷取執行預存程序後的輸出參數            string name = cmd.Parameters["@name"].Value.ToString();            Response.Write(name);        }        catch (Exception ex)        {            Response.Write(ex.Message);            if (conn.State == ConnectionState.Open)            {                conn.Close();            }        }        finally        {            if (conn.State == ConnectionState.Open)            {                conn.Close();            }        } 

    運行ASPX頁面,則能夠看到執行預存程序後返回的結果!
    需要注意的是如果輸出參數是varchar類型的話則必須定義長度,否則會出錯,如果輸出參數是數字型的話就不必定義長度了!
    下面是完整的ProcTest.aspx.cs的源碼: C#代碼

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Web;   
  5. using System.Web.UI;   
  6. using System.Web.UI.WebControls;   
  7. using System.Data;   
  8. using System.Data.SqlClient;   
  9.   
  10. public partial class ProcTest : System.Web.UI.Page   
  11. {   
  12.     protected void Page_Load(object sender, EventArgs e)   
  13.     {   
  14.         // 建立連接字串,在正式項目中可放在web.config中   
  15.         string connStr = "server=niunan\\sqlexpress;uid=sa;pwd=123456;database=logintest";   
  16.         // 串連資料庫   
  17.         SqlConnection conn = new SqlConnection(connStr);   
  18.   
  19.         try  
  20.         {   
  21.             // 開啟資料庫連接   
  22.             conn.Open();   
  23.             // 建立用於執行資料庫操作的命令對象, GetUNameById為預存程序名稱   
  24.             SqlCommand cmd = new SqlCommand("GetUNameById", conn);   
  25.             // 設定執行命令的方式為預存程序   
  26.             cmd.CommandType = CommandType.StoredProcedure;   
  27.   
  28.             // 向命令對象添加預存程序所需要的參數   
  29.             cmd.Parameters.Add("@uid", SqlDbType.Int);   
  30.             // 設定要傳入到預存程序的參數值   
  31.             cmd.Parameters["@uid"].Value = 2;   
  32.   
  33.             // 添加預存程序中的輸出參數   
  34.             cmd.Parameters.Add("@name", SqlDbType.VarChar, 50);   
  35.             // 設定參數為output輸出參數   
  36.             cmd.Parameters["@name"].Direction = ParameterDirection.Output;   
  37.   
  38.             // 執行預存程序   
  39.             cmd.ExecuteReader();   
  40.   
  41.             // 擷取執行預存程序後的輸出參數   
  42.             string name = cmd.Parameters["@name"].Value.ToString();   
  43.   
  44.             Response.Write(name);   
  45.         }   
  46.         catch (Exception ex)   
  47.         {   
  48.             Response.Write(ex.Message);   
  49.             if (conn.State == ConnectionState.Open)   
  50.             {   
  51.                 conn.Close();   
  52.             }   
  53.         }   
  54.         finally  
  55.         {   
  56.             if (conn.State == ConnectionState.Open)   
  57.             {   
  58.                 conn.Close();   
  59.             }   
  60.         }    
  61.     }   
  62. }  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.