将带参数的存储过程传递给c#中的函数

时间:2013-03-12 11:29:30

标签: c# sql-server

如何将带参数的存储过程传递给函数。

我实际上有一个将数据插入数据库的功能.. 即时通讯寻找一种方式,我可以通过参数传递SP 插入函数以重用插入数据代码。

1 个答案:

答案 0 :(得分:1)

将调用放入方法中的存储过程,并从要调用它的任何位置调用此方法。将参数(字符串,整数,双精度数等)传递给此方法,并将这些值放入存储过程的参数中。

这样您就可以将所有SP代码保存在一个位置。

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;
        }
    }
}
相关问题