C#執行預存程序代碼執行個體

來源:互聯網
上載者:User

   C#執行預存程序代碼執行個體,示範如何用C#調用並執行SQLSERVER的預存程序,是一個資料庫的進階應用程式,預存程序相對專業些,但效率更高,而且使SQL的功能發揮的更強大,這僅是一個較簡單的預存程序調用例子:

  01using System;

  02using System.Data;

  03using System.Data.SqlClient;

  04namespace ExecuteStorageProcess

  05{

  06 public class ExecuteStorageProcess

  07 {

  08 public static void Main()

  09 {

  10 SqlConnection mySqlConnection =

  11 new SqlConnection(

  12 "server=localhost;database=Northwind;uid=sa;pwd=sa"

  13 );

  14 mySqlConnection.Open();

  15 // 設定CommandText屬性為EXECUTE語句

  16 SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

  17 mySqlCommand.CommandText =

  18 "EXECUTE AddProduct @MyProductID OUTPUT, @MyProductName, " +

  19 "@MySupplierID, @MyCategoryID, @MyQuantityPerUnit, " +

  20 "@MyUnitPrice, @MyUnitsInStock, @MyUnitsOnOrder, " +

  21 "@MyReorderLevel, @MyDiscontinued";

  22 // 添加程序呼叫所要用到的參數

  23 mySqlCommand.Parameters.Add("@MyProductID", SqlDbType.Int);

  24 mySqlCommand.Parameters["@MyProductID"].Direction =

  25 ParameterDirection.Output;

  26 mySqlCommand.Parameters.Add(

  27 "@MyProductName", SqlDbType.NVarChar, 40).Value = "Widget";

  28 mySqlCommand.Parameters.Add(

  29 "@MySupplierID", SqlDbType.Int).Value = 1;

  30 mySqlCommand.Parameters.Add(

  31 "@MyCategoryID", SqlDbType.Int).Value = 1;

  32 mySqlCommand.Parameters.Add(

  33 "@MyQuantityPerUnit", SqlDbType.NVarChar, 20).Value = "1 per box";

  34 mySqlCommand.Parameters.Add(

  35 "@MyUnitPrice", SqlDbType.Money).Value = 5.99;

  36 mySqlCommand.Parameters.Add(

  37 "@MyUnitsInStock", SqlDbType.SmallInt).Value = 10;

  38 mySqlCommand.Parameters.Add(

  39 "@MyUnitsOnOrder", SqlDbType.SmallInt).Value = 5;

  40 mySqlCommand.Parameters.Add(

  41 "@MyReorderLevel", SqlDbType.SmallInt).Value = 5;

  42 mySqlCommand.Parameters.Add(

  43 "@MyDiscontinued", SqlDbType.Bit).Value = 1;

  44 // 執行命令

  45 mySqlCommand.ExecuteNonQuery();

  46 // 讀取輸出參數的值

  47 Console.WriteLine("New ProductID = " +

  48 mySqlCommand.Parameters["@MyProductID"].Value);

  49 mySqlConnection.Close();

  50 }

  51 }

  52}

  本代碼不包括資料庫的預存程序實體,你可以自己手動建立一個。

        注:更多精彩文章請關注三聯編程教程欄目。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.