使用 ADO.NET 访问输出参数值
本指南演示如何在 ADO.NET 应用程序中有效检索输出参数值。 正确处理输出参数对于许多数据库交互至关重要。
在存储过程中定义输出参数
要在存储过程中声明输出参数,请使用以下语法:
<code class="language-sql">@ParameterName DATATYPE OUTPUT</code>
示例:
<code class="language-sql">@ID INT OUTPUT</code>
检索 ADO.NET 代码中的输出参数值
以下步骤详细介绍了如何在 C# 代码中访问输出参数值:
<code class="language-csharp">// Create a SqlParameter for the output parameter, specifying name, type, and direction. SqlParameter outputParameter = new SqlParameter("@ID", SqlDbType.Int); outputParameter.Direction = ParameterDirection.Output; // Add the output parameter to the SqlCommand's Parameters collection. cmd.Parameters.Add(outputParameter); // Execute the stored procedure. cmd.ExecuteNonQuery(); // Access the output parameter's value after execution. int id = (int)outputParameter.Value; </code>
重要提示:
SqlDbType
时使用的SqlParameter
必须与存储过程中输出参数的数据类型精确匹配。outputParameter.Value
转换为正确的数据类型(例如 int
、string
、DateTime
)。null
值的情况。 这可以防止运行时错误。以上是如何在 ADO.NET 中检索输出参数值?的详细内容。更多信息请关注PHP中文网其他相关文章!