帮我看看select语句,我应怎样写才对?
CS:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[ "SQLConnString1 "].ConnectionString);
string strsql = "select * from Item where 1=1 ";
SqlCommand myCommand = new SqlCommand(strsql, conn);
string Pid = Request.QueryString[ "Pid "];
if (Pid != null)
{
myCommand.Parameters.Add(new SqlParameter( "@Pid ", SqlDbType.VarChar, 50));
myCommand.Parameters[ "@Pid "].Value = Pid;
strsql += " and ProductId=@Pid "; //参数不起作用。应怎么写才对呢?
}
conn.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
DataList1.DataSource = myReader;
DataList1.DataBind();
conn.Close();
}
}
[解决办法]
CS:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[ "SQLConnString1 "].ConnectionString);
string strsql = "select * from Item where 1=1 ";
SqlCommand myCommand = null;
string Pid = Request.QueryString[ "Pid "];
if (Pid != null)
{
strsql += " and ProductId=@Pid ";
myCommand = new SqlCommand(strsql, conn);
myCommand.Parameters.Add(new SqlParameter( "@Pid ",SqlDbType.VarChar, 50));
myCommand.Parameters[ "@Pid "].Value = Pid;
//参数不起作用。应怎么写才对呢?
}else
{
myCommand= new SqlCommand(strsql, conn);
}
conn.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
DataList1.DataSource = myReader;
DataList1.DataBind();
conn.Close();
}
}
[解决办法]
if (Pid != null)
{
myCommand.CommandText =myCommand.CommandText + " and ProductId=@Pid "
myCommand.Parameters.Add(new SqlParameter( "@Pid ", SqlDbType.VarChar, 50));
myCommand.Parameters[ "@Pid "].Value = Pid;
}