过程或函数sp_select_companydetails指定了太多参数

本文关键字:太多 参数 select 函数 sp 过程 companydetails | 更新日期: 2023-09-27 18:04:41

我真的对这个错误感到沮丧,所有功能代码都是正确的,但仍然给我错误,我试图从SQL Server数据库选择信息。

存储过程:

create procedure sp_select_companydetails
    @id varchar(5)
as
begin
    select company_name, company_address 
    from CompanyDetails
end
c#代码:

2)在表单按钮上单击事件

string id = "1";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_select_companydetails";
cmd.Parameters.Add("@id", id);
FillDataset();
在课堂上

public DataSet FillDataset()
{
    try
    {
        using (cmd)
        {
            DataSet ds = new DataSet();
            cmd.Connection = con;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            cmd.Parameters.Clear();
            return ds;
        }
    }
    catch (Exception)
    {
        throw;
    }
}

当我点击表单按钮时,我得到这个错误:

过程或函数sp_select_companydetails指定的参数太多。

建议一个好的解决方案

提前感谢

过程或函数sp_select_companydetails指定了太多参数

不要使用全局SqlCommand,而是在每次需要时创建它。当您处理一次性对象

时,建议使用这种方法。
using (SqlConnection con = new SqlConnection(GetConnectionString())
using (SqlCommand myCmd = new SqlCommand("sp_select_companydetails", con))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = "1";
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    return ds;
}

顺便说一下,我们看不出你是如何创建SqlConnection的,但似乎你在全局级别上保留了另一个一次性对象。这对于SqlConnection来说尤其糟糕,因为该对象在客户端和服务器上都保留对系统范围资源的引用。不要创建全局连接对象,只需创建一个全局方法,该方法返回当前连接字符串,以便在创建本地SqlConnection(上面示例中的GetConnectionString())时使用。如果您认为这是性能杀手,我建议您阅读连接池的概念