我只想使用我的cookie值从数据库中选择所有数据。但它只打印最后添加的值。帮助我 [英] i just want to select all data from database using my cookies value.but it printing only the last added value.help me

查看:62
本文介绍了我只想使用我的cookie值从数据库中选择所有数据。但它只打印最后添加的值。帮助我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["shopkart"].ConnectionString);
        ArrayList colCookies = new ArrayList();
        for (int i = 0; i < Request.Cookies.Count; i++)
        
        {
               
                string cmdtxt = "SELECT * from productTables WHERE productid='"+ Request.Cookies[i].Name +"' ";
                SqlCommand cmd = new SqlCommand(cmdtxt, con);
                
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();

                lstViewEmployeeDetails1.DataSource = dr;
                lstViewEmployeeDetails1.DataBind();

                con.Close();
           
        }
       
    }

推荐答案

List<string> ids =new List<string>();
for (int i = 0; i < Request.Cookies.Count; i++)
{
  ids.Add("'"+Request.Cookies[i].Name+"'");
}
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["shopkart"].ConnectionString);

string cmdtxt = string.Format("SELECT * from productTables WHERE productid in({0})", string.Join("," ,ids));
SqlCommand cmd = new SqlCommand(cmdtxt, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
lstViewEmployeeDetails1.DataSource = dr;
lstViewEmployeeDetails1.DataBind();
con.Close();



问题是您是每个产品ID的绑定数据,最后您只有最终产品数据。如上所述更改sql语句以在单个查询中检索所有产品ID的数据。


problem is you are binding data for each product id and at the end you have final product data only. change the sql statement as above to retrieve data for all the product ids in single query.


您正在运行cookie值的循环,并在每次迭代中将当前数据指定为数据源到列表视图...所以第二次迭代会覆盖第一次和第三次第二次,最后一次重写最后一次,这将留给你最后一次......

你必须要了解分配数据源而不是将新内容与现有内容合并但是替换它...

您应该做的是构建一个更好的SQL查询及其中的所有cookie(作为条件)并运行一次查询并分配一次结果......
You are running a loop over the cookie values and in each iteration you assign the current data as data source to the list-view...So the second iteration overwrites the first and the third the second and the last the one before last, which leaves you with the last...
You have to understand the assigning data source not merging the new with the existing but replaces it...
What you should do is to built a better SQL query with all the cookies in it (as conditions) and run once the query and assign once the result...


这篇关于我只想使用我的cookie值从数据库中选择所有数据。但它只打印最后添加的值。帮助我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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