亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在ADO.NET中獲取輸出參數值

在ADO.NET中獲取輸出參數值

拉風的咖菲貓 2019-07-30 17:03:20
在ADO.NET中獲取輸出參數值我的存儲過程有一個輸出參數:@ID INT OUT如何使用ado.net檢索此內容?using (SqlConnection conn = new SqlConnection(...)){     SqlCommand cmd = new SqlCommand("sproc", conn);     cmd.CommandType = CommandType.StoredProcedure;     // add parameters     conn.Open();     // *** read output parameter here, how?     conn.Close();}
查看完整描述

3 回答

?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

其他反應表明這一點,但實際上你只需要創建一個SqlParameter,設置DirectionOutput,并把它添加到SqlCommandParameters集合。然后執行存儲過程并獲取參數的值。

使用您的代碼示例:

// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'susing (SqlConnection conn = new SqlConnection(connectionString))using (SqlCommand cmd = new SqlCommand("sproc", conn)){
   // Create parameter with Direction as Output (and correct name and type)
   SqlParameter outputIdParam = new SqlParameter("@ID", SqlDbType.Int)
   { 
      Direction = ParameterDirection.Output 
   };

   cmd.CommandType = CommandType.StoredProcedure;
   cmd.Parameters.Add(outputIdParam);

   conn.Open();
   cmd.ExecuteNonQuery();

   // Some various ways to grab the output depending on how you would like to
   // handle a null value returned from the query (shown in comment for each).

   // Note: You can use either the SqlParameter variable declared
   // above or access it through the Parameters collection by name:
   //   outputIdParam.Value == cmd.Parameters["@ID"].Value

   // Throws FormatException
   int idFromString = int.Parse(outputIdParam.Value.ToString());

   // Throws InvalidCastException
   int idFromCast = (int)outputIdParam.Value; 

   // idAsNullableInt remains null
   int? idAsNullableInt = outputIdParam.Value as int?; 

   // idOrDefaultValue is 0 (or any other value specified to the ?? operator)
   int idOrDefaultValue = outputIdParam.Value as int? ?? default(int); 

   conn.Close();}

在獲取時要小心Parameters[].Value,因為需要將類型轉換為object您聲明的類型。而SqlDbType當您創建使用SqlParameter需求來匹配數據庫類型。如果您只是將其輸出到控制臺,您可能只是在使用Parameters["@Param"].Value.ToString()(通過Console.Write()String.Format()調用顯式或隱式)。


查看完整回答
反對 回復 2019-07-30
  • 3 回答
  • 0 關注
  • 739 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號