ADO.NET调用带输入输出的存储过程

雅轩聊科技 2024-11-21 20:48:37

在ADO.NET中调用带输入和输出参数的存储过程,通常使用SqlCommand对象来执行存储过程,并通过其Parameters集合来设置和获取参数值。以下是一个示例,展示了如何调用一个带输入和输出参数的存储过程。

假设我们有一个存储过程GetEmployeeDetails,其定义如下:

CREATE PROCEDURE GetEmployeeDetails @EmployeeID INT, @EmployeeName NVARCHAR(100) OUTPUTASBEGIN SELECT @EmployeeName = Name FROM Employees WHERE ID = @EmployeeID;END

这个存储过程接受一个输入参数@EmployeeID,并输出一个参数@EmployeeName。

下面是使用ADO.NET调用这个存储过程的C#代码示例:

using System;using System.Data;using System.Data.SqlClient;class Program{ static void Main() { string connectionString = "your_connection_string_here"; int employeeId = 1; // 示例员工ID using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand("GetEmployeeDetails", connection); command.CommandType = CommandType.StoredProcedure; // 添加输入参数 SqlParameter inputParam = new SqlParameter("@EmployeeID", SqlDbType.Int); inputParam.Value = employeeId; command.Parameters.Add(inputParam); // 添加输出参数 SqlParameter outputParam = new SqlParameter("@EmployeeName", SqlDbType.NVarChar, 100) { Direction = ParameterDirection.Output }; command.Parameters.Add(outputParam); try { connection.Open(); command.ExecuteNonQuery(); // 获取输出参数的值 string employeeName = (string)outputParam.Value; Console.WriteLine($"Employee Name: {employeeName}"); } catch (Exception ex) { Console.WriteLine("An error occurred: " + ex.Message); } } }}

代码说明:连接字符串:connectionString:替换为您的数据库连接字符串。创建SqlConnection对象:使用using语句确保连接正确关闭和释放资源。创建SqlCommand对象:设置命令类型为CommandType.StoredProcedure,并指定存储过程名称。添加输入参数:创建一个SqlParameter对象,设置其名称、类型和值,并将其添加到命令的参数集合中。添加输出参数:创建一个SqlParameter对象,设置其名称、类型、大小和方向(ParameterDirection.Output),并将其添加到命令的参数集合中。执行存储过程:打开连接,调用ExecuteNonQuery方法执行存储过程。获取输出参数的值:从输出参数对象中获取其值,并输出到控制台。异常处理:使用try-catch块捕获并处理任何可能发生的异常。

通过以上步骤,您可以使用ADO.NET成功调用带输入和输出参数的存储过程,并获取其输出值。

0 阅读:5

雅轩聊科技

简介:感谢大家的关注