0

パラメータを含むストアド プロシージャを関数に渡す方法を教えてください。

私は実際にデータベースにデータを挿入する関数を持っています.挿入データコードを再利用するために、その挿入関数にパラメーターを指定してSPを渡す方法を探しています。

4

1 に答える 1

1

ストアドプロシージャへの呼び出しをメソッドに入れ、呼び出したい場所からこのメソッドを呼び出します。パラメータ(strings、ints、doubles、...)をこのメソッドに渡し、これらの値をストアドプロシージャのパラメータに入れます。

このようにして、すべてのSPコードを1か所に保管します。

public class CustomerProvider
{
    public int UpdateCustomer(int id, string name, string address)
    {
        using(connection = new
            SqlConnection("Server=localhost;DataBase=Northwind;Integrated Security=SSPI"))
        {
            connection.Open();

            var command = new SQLCommand("csp_updatecustomer", connection);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(
            new SqlParameter("@CustomerID", id));
            command.Parameters.Add(
                new SqlParameter("@CustomerName", name));
            command.Parameters.Add(
                new SqlParameter("@CustomerAddress", address));
            var result = command.ExecuteNonQuery();
            return result;
        }
    }
}
于 2013-03-12T11:32:22.773 に答える