ADO.NET存储过程调用案例分析(含输入参数)

2025-01-02 01:42:01   小编

ADO.NET存储过程调用案例分析(含输入参数)

在.NET开发中,ADO.NET提供了强大的数据访问功能,其中存储过程的调用是一项重要的技术。存储过程是一组预编译的SQL语句,它可以提高数据库的性能和安全性。本文将通过一个具体的案例来分析如何在ADO.NET中调用带有输入参数的存储过程。

我们需要在数据库中创建一个存储过程。假设我们有一个名为“Customers”的表,其中包含“CustomerID”、“CustomerName”和“ContactNumber”等字段。我们创建一个存储过程“GetCustomerByID”,用于根据客户ID获取客户信息。存储过程的代码如下:

CREATE PROCEDURE GetCustomerByID
    @CustomerID INT
AS
BEGIN
    SELECT CustomerID, CustomerName, ContactNumber
    FROM Customers
    WHERE CustomerID = @CustomerID
END

接下来,我们在.NET应用程序中调用这个存储过程。以下是使用C#语言的示例代码:

using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "YourConnectionString";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand("GetCustomerByID", connection);
            command.CommandType = CommandType.StoredProcedure;

            // 添加输入参数
            SqlParameter parameter = new SqlParameter("@CustomerID", SqlDbType.Int);
            parameter.Value = 1;
            command.Parameters.Add(parameter);

            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine($"CustomerID: {reader["CustomerID"]}, CustomerName: {reader["CustomerName"]}, ContactNumber: {reader["ContactNumber"]}");
            }
            reader.Close();
        }
    }
}

在上述代码中,我们首先创建了一个SqlConnection对象,并指定了连接字符串。然后,创建了一个SqlCommand对象,并将存储过程的名称和连接对象传递给它。接着,通过设置CommandType属性为CommandType.StoredProcedure来指定这是一个存储过程调用。

我们还创建了一个SqlParameter对象,用于传递输入参数。最后,打开连接,执行存储过程,并读取返回的结果。

通过这个案例,我们可以看到在ADO.NET中调用带有输入参数的存储过程的基本步骤。这种方法可以提高数据库的性能和安全性,同时也方便了代码的维护和管理。

TAGS: 案例分析 输入参数 存储过程 ADO.NET

欢迎使用万千站长工具!

Welcome to www.zzTool.com