获取在ADO.NET输出参数值参数、ADO、NET

2023-09-02 21:08:03 作者:心易老

我的存储过程有一个输出参数:

  @ID int的列
 

我怎样才能检索到使用ado.net?

 使用(SqlConnection的康恩=新的SqlConnection(...))
{
    的SqlCommand CMD =新的SqlCommand(存储过程,康涅狄格州);
    cmd.CommandType = CommandType.StoredProcedure;

    //添加参数

    conn.Open();

    // ***读到这里输出参数,怎么样?
    conn.Close();
}
 

解决方案

另外的反应显示了这一点,但实际上你只需要创建一个的SqlParameter ,将方向输出,并将其添加到的SqlCommand 参数集合。然后执行存储过程,并获得该参数的值。

使用您的code样品:

  // SqlConnection和SqlCommand的是IDisposable的,所以堆栈使用一对()的
使用(SqlConnection的康恩=新的SqlConnection(的connectionString))
使用(CMD的SqlCommand =新的SqlCommand(存储过程,康涅狄格州))
{
   //与方向输出(正确名称和类型)创建参数
   的SqlParameter outputIdParam =新的SqlParameter(@ ID,SqlDbType.Int)
   {
      方向= ParameterDirection.Output
   };

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

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

   //一些不同的方式来获取输出取决于你怎么想
   //处理来自查询(在注释中示出)返回一个空值。

   //注意:您可以使用该的SqlParameter变量声明
   //以上或名称通过参数集合访问它:
   // outputIdParam.Value == cmd.Parameters [@ ID。价值

   //抛出出现FormatException
   INT idFromString = int.Parse(outputIdParam.Value.ToString());

   //抛出InvalidCastException的
   INT idFromCast =(INT)outputIdParam.Value;

   // idAsNullableInt仍然空
   诠释? idAsNullableInt = outputIdParam.Value为INT?;

   // idOrDefaultValue为0(或指定的ΔΣ操作者的任何其它值)
   INT idOrDefaultValue = outputIdParam.Value为INT? ?默认值(INT);

   conn.Close();
}
 
ADO.NET数据访问技术

获得时要小心参数[]。值,因为类型需要从对象来投你在声明它。而的SqlDbType 在创建的SqlParameter 需要匹配的数据库类型使用。如果你打算只输出到控制台,你可能只是使用参数[@参数。Value.ToString()(无论是显式或隐式地通过一个 Console.Write()的String.Format()电话)。

编辑:大于3.5年,几乎20K的意见,没有人费心去提它甚至没有编译在原来的岗位我小心的评论中指定的原因。美观大方。固定它基于来自@Walter Stabosz和@Stephen肯尼迪和匹配来自@abatishchev问题的更新code编辑的好评。

My stored procedure has an output parameter:

@ID INT OUT

How can I retrieve this using 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();
}

解决方案

The other response shows this, but essentially you just need to create a SqlParameter, set the Direction to Output, and add it to the SqlCommand's Parameters collection. Then execute the stored procedure and get the value of the parameter.

Using your code sample:

// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s
using (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();
}

Be careful when getting the Parameters[].Value, since the type needs to be cast from object to what you're declaring it as. And the SqlDbType used when you create the SqlParameter needs to match the type in the database. If you're going to just output it to the console, you may just be using Parameters["@Param"].Value.ToString() (either explictly or implicitly via a Console.Write() or String.Format() call).

EDIT: Over 3.5 years and almost 20k views and nobody had bothered to mention that it didn't even compile for the reason specified in my "be careful" comment in the original post. Nice. Fixed it based on good comments from @Walter Stabosz and @Stephen Kennedy and to match the update code edit in the question from @abatishchev.