如何从C#中的另一个类文件调用sp函数 [英] How to call sp function from another class file in C#

查看:373
本文介绍了如何从C#中的另一个类文件调用sp函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的朋友们,



我有以下程序类文件。我想从另一个类文件中调用此函数。但我的sp有参数如何在这个函数中添加参数。



我尝试过:



Dear Friends,

I have procedure class file below. i want to call this function from another class file. but my sp have parameters how to add parameters in this function.

What I have tried:

public int intSPExecuteNonQuery(string StoredProcName)
        {
            using (SqlCommand cmd = new SqlCommand(StoredProcName))
            {
                cmd.CommandType = CommandType.StoredProcedure;               
                cmd.Connection = connection;
                connection.Open();
                cmd.ExecuteNonQuery();
                connection.Close();
                return 1;
            }
        }





另一个班级档案:



another class file:

return intSPExecuteNonQuery("spItems")

推荐答案

在方法<中添加一个额外的参数[ SqlParameterCollection ] br />
Add an additional parameter [SqlParameterCollection] to the method
public int intSPExecuteNonQuery(string StoredProcName, SqlParameterCollection parameters)
        {
            using (SqlCommand cmd = new SqlCommand(StoredProcName))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = connection;
                cmd.Parameters = parameters;
                connection.Open();
                cmd.ExecuteNonQuery();
                connection.Close();
                return 1;
            }
        }





用法:



usage:

return intSPExecuteNonQuery("spItems", null);




SqlParameter param1 = new SqlParameter("@param1", "Param value");
            SqlParameter param2 = new SqlParameter("@param2", "Param value");
            return intSPExecuteNonQuery("SPName", new SqlParameterCollection() { param1,param2 });


是的,你可以:

Yes, you can:
public int intSPExecuteNonQuery(string StoredProcName, params SqlParameter[] data)
    {
    using (SqlCommand cmd = new SqlCommand(StoredProcName))
        {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = connection;
        foreach (SqlParameter p in data)
            {
            cmd.Parameters.Add(p);
            }
        connection.Open();
        cmd.ExecuteNonQuery();
        connection.Close();
        return 1;
        }
    }


这篇关于如何从C#中的另一个类文件调用sp函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆