在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
,设置Direction
来Output
,并把它添加到SqlCommand
的Parameters
集合。然后执行存储过程并获取参数的值。
使用您的代码示例:
// 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()
调用显式或隐式)。
- 3 回答
- 0 关注
- 684 浏览
添加回答
举报
0/150
提交
取消