我可以将SqlParameterCollection对象传递到SQL命令中吗

问题描述

| 我目前有一个连接类,可以处理所有数据库连接。我想做的是在一页上建立一个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(); 
}
    

解决方法

        基本上,在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
var P = new SqlCommand().Parameters;