【问题标题】:Can I pass a SqlParameterCollection object into a SQL Command我可以将 SqlParameterCollection 对象传递给 SQL 命令吗
【发布时间】:2011-06-12 07:31:51
【问题描述】:

我目前有一个连接类来处理我所有的数据库连接。我想要做的是在一页上构建一个 SqlParameterCollection 对象,然后将该对象传递给我的连接类。是否有可能做到这一点?我没有收到任何编译错误,但我无法获得要识别的参数。这是我想要做的:

Page 1: 

    string sql = null;
conn.strConn = connectionstring;

sql = "sqlstring";

SqlParameterCollection newcollect = null;
newcollect.Add("@Switch",1);

conn.OpenReader(sql, newcollect);
while (conn.DR.Read())
{
        read data onto page here...
}
conn.CloseReader();

Page 2 (connection class) :

public void OpenReader(string sql, SqlParameterCollection collect)
{
        Conn = new SqlConnection(strConn);
        Conn.Open();
        Command = new SqlCommand(sql,Conn);

        Command.Parameters.Add(collect);  <------This is the root of my question
        Command.CommandTimeout = 300;
        // executes sql and fills data reader with data
        DR = Command.ExecuteReader(); 
}

【问题讨论】:

  • 另外,在将项目添加到您的收藏之前,您需要对其进行初始化!这不起作用:SqlParameterCollection newcollect = null - 您需要在代码中的某处使用SqlParameterCollection newcollect = new SqlParameterCollection();添加任何项目...

标签: parameter-passing sqlparameter


【解决方案1】:

基本上,在 ASP.NET 中,要从一个页面到另一个页面持久化某些内容,您需要使用会话状态并将您的对象放在那里 - 所以您可以尝试这样的事情:

第 1 页:

List<SqlParameter> newcollect = new List<SqlParameter>();
newcollect.Add(new SqlParameter("@Switch", 1));

Session["SqlParameters"] = newcollect;

第 2 页(连接类):

public void OpenReader(string sql)
{
    Conn = new SqlConnection(strConn);
    Conn.Open();

    Command = new SqlCommand(sql,Conn);

    List<SqlParameter> coll = null;
    if(Session["SqlParameters"] != null)
    {
       coll = (List<SqlParameter>)Session["SqlParameters"];
    }

    Command.Parameters.AddRange(coll.ToArray());
    Command.CommandTimeout = 300;
    // executes sql and fills data reader with data
    DR = Command.ExecuteReader(); 
}

这将起作用 - 如果您在 ASP.NET 站点上启用了会话状态。如果您的网站由于某种原因无法使用会话状态内存(例如,如果您在 webfarm 上并且无法使用 SQL Server 进行会话状态),这将不起作用

【讨论】:

  • 语句“SqlParameterCollection newcollect = new SqlParameterCollection();”给出以下错误: - 错误 1 ​​类型“System.Data.SqlClient.SqlParameterCollection”没有定义构造函数
  • @Muhammed Rauf K:好的,你需要改用List&lt;SqlParameter&gt; - 太糟糕了,MS 选择让这个集合类不可实例化......
  • 是的。我用like.. List spParamList = new List();
【解决方案2】:

你可以像这样实例化一个新的SqlParameterCollection

var P = new SqlCommand().Parameters;

【讨论】:

    猜你喜欢
    • 2017-10-09
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多