熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

C#調用存儲過程簡單完整例子

2022-06-13   來源: .NET編程 

  CREATE PROC P_TEST @Name VARCHAR() @Rowcount INT OUTPUT AS BEGIN SELECT * FROM T_Customer WHERE NAME=@Name SET @Rowcount=@@ROWCOUNT END GO

  存儲過程調用如下:

  

  DECLARE @i INT EXEC P_TEST A@i OUTPUT SELECT @i 結果

  /* Name Address Tel

  A Address Telphone (所影響的行數為 行) (所影響的行數為 行)

  */ DotNet 部分(C#) WebConfig 文件:

  C#代碼:(用到兩個測試控件DataGrid(用於顯示綁定結果集合)Lable(用於顯示存儲過程返回單值)

  //添加數據庫引用

  代碼

  using SystemDataSqlClient;

   private void Page_Load(object sender SystemEventArgs e)

  { // 在此處放置用戶代碼以初始化頁面

  String DBConnStr; DataSet MyDataSet=new DataSet();

  SystemDataSqlClientSqlDataAdapter DataAdapter=new SystemDataSqlClientSqlDataAdapter();

  DBConnStr=SystemConfigurationConfigurationSettingsAppSettings[ConnectString];

  SystemDataSqlClientSqlConnection myConnection = new SystemDataSqlClientSqlConnection(DBConnStr);

  if (myConnectionState!=ConnectionStateOpen)

  { myConnectionOpen(); }

  SystemDataSqlClientSqlCommand myCommand = new SystemDataSqlClientSqlCommand(P_TestmyConnection);

  myCommandCommandType=CommandTypeStoredProcedure; //添加輸入查詢參數賦予值

  myCommandParametersAdd(@NameSqlDbTypeVarChar);

  myCommandParameters[@Name]Value =A; //添加輸出參數

  myCommandParametersAdd(@RowcountSqlDbTypeInt);

  myCommandParameters[@Rowcount]Direction=ParameterDirectionOutput;

  myCommandExecuteNonQuery();

  DataAdapterSelectCommand = myCommand;

  if (MyDataSet!=null)

  { DataAdapterFill(MyDataSettable); }

  DataGridDataSource=MyDataSet; DataGridDataBind(); //得到存儲過程輸出參數

  LabelText=myCommandParameters[@Rowcount]ValueToString();

  if (myConnectionState == ConnectionStateOpen) { myConnectionClose();

  }

  }

  

  運行以上代碼即可(返回記錄集合和存儲過程返回值)


From:http://tw.wingwit.com/Article/program/net/201311/13759.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.