【问题标题】:How can I update the database table from a datalist?如何从数据列表更新数据库表?
【发布时间】:2019-08-21 20:03:02
【问题描述】:

我正在建立一个电子商务网站,我使用数据列表来显示我的产品,当我按下“添加到购物车”按钮时,它们应该被添加到数据库表中,但由于某种原因,产品没有在数据库表中更新。此外,单击第一个产品会出现错误提示“已经有一个打开的阅读器”,并且显示错误的行是“int result = comm.ExecuteNonQuery();”

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Globalization;

namespace MWM1812
{
    public partial class productCatalog : System.Web.UI.Page
    {
        public enum MessageType { Success, Error, Info, Warning };
        protected void ShowMessage(string Message, MessageType type)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), System.Guid.NewGuid().ToString(), "ShowMessage('" + Message + "','" + type + "');", true);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }




        protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "AddToCart")
            {
                Session["uid"] = 1;
                Label lbl = (Label)e.Item.FindControl("PIDLabel");
                lblAtC.Text = lbl.Text;
                ShowMessage("Product successfully added to Cart", MessageType.Success);

                string connStr = ConfigurationManager.ConnectionStrings["MWM1812ConnString"].ConnectionString;
                SqlConnection conn = new SqlConnection(connStr);

                conn.Open();

                string sqlQuery = "SELECT * FROM tblShoppingCart WHERE uid=@uid AND pid=@pid";
                SqlCommand comm = new SqlCommand(sqlQuery, conn);
                comm.Parameters.AddWithValue("@uid", Session["uid"]);
                comm.Parameters.AddWithValue("@pid", lblAtC.Text.Trim());
                using (SqlDataReader reader = comm.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        string sqlQuery2 = "UPDATE tblShoppingCart SET qty=qty+1 WHERE uid=@uid AND pid=@pid";
                        SqlCommand comm1 = new SqlCommand(sqlQuery2, conn);
                        comm1.Parameters.AddWithValue("@qty", 1);
                        comm1.Parameters.AddWithValue("@dtShopped", DateTime.Now.ToString());
                        //// Add code for adding parameters and executing sqlQuery2 
                        int result = comm1.ExecuteNonQuery();
                    }
                    else
                    {



                        string sqlQuery1 = "INSERT INTO tblShoppingCart (uid, pid, qty, dtShopped) VALUES (@uid, @pid, @qty, @dtShopped)";
                        SqlCommand comma = new SqlCommand(sqlQuery1, conn);
                        comma.Parameters.AddWithValue("@uid", Session["uid"]);
                        comma.Parameters.AddWithValue("@pid", lblAtC.Text);
                        comma.Parameters.AddWithValue("@qty", 1);
                        //comm.Parameters.AddWithValue("@dtShopped", DateTime.Now.ToLongDateString());
                        comma.Parameters.AddWithValue("@dtShopped", DateTime.Now.ToString());

                        int result = comma.ExecuteNonQuery();


                    }
                }
            }
        }
    }
}

【问题讨论】:

    标签: c# asp.net database datalist


    【解决方案1】:

    尝试像这样更新代码:

    if (e.CommandName == "AddToCart") {
         bool productExists = false;
    
         Session["uid"] = 1;
         Label lbl = (Label) e.Item.FindControl("PIDLabel");
         lblAtC.Text = lbl.Text;
         ShowMessage("Product successfully added to Cart", MessageType.Success);
    
         string connStr = ConfigurationManager.ConnectionStrings["MWM1812ConnString"].ConnectionString;
         SqlConnection conn = new SqlConnection(connStr);
    
         conn.Open();
    
         string sqlQuery = "SELECT * FROM tblShoppingCart WHERE uid=@uid AND pid=@pid";
         SqlCommand comm = new SqlCommand(sqlQuery, conn);
         comm.Parameters.AddWithValue("@uid", Session["uid"]);
         comm.Parameters.AddWithValue("@pid", lblAtC.Text.Trim());
    
         using(SqlDataReader reader = comm.ExecuteReader()) {    
            productExists = reader.HasRows;
         }
    
          if (productExists) {
           string sqlQuery2 = "UPDATE tblShoppingCart SET qty=qty+1 WHERE uid=@uid AND pid=@pid";
    
           // Add code for adding parameters and executing sqlQuery2 
          } else {
    
    
    
            string sqlQuery1 = "INSERT INTO tblShoppingCart (uid, pid, qty, dtShopped) VALUES (@uid, @pid, @qty, @dtShopped)";
            SqlCommand comma = new SqlCommand(sqlQuery, conn);
            comma.Parameters.AddWithValue("@uid", Session["uid"]);
            comma.Parameters.AddWithValue("@pid", lblAtC.Text);
            comma.Parameters.AddWithValue("@qty", 1);
            //comm.Parameters.AddWithValue("@dtShopped", DateTime.Now.ToLongDateString());
            comma.Parameters.AddWithValue("@dtShopped", DateTime.Now.ToString());
    
            int result = comma.ExecuteNonQuery();
    
    
          }     
        }
    

    注意使用 reader.HasRows 属性来确定产品是否已经存在。此外,SqlDataReader 被包裹在 using 块中以便将其丢弃。

    【讨论】:

    • 我试过了,但它给出了相同的“已经有一个打开的 DataReader 与此命令关联,必须先关闭。”错误
    • 您是否已将完整代码作为问题的一部分发布?另外,您在哪一行代码中遇到了这个异常?
    • 是的,这是整个页面的代码。问题在于 int result = comm.ExecuteNonQuery();
    • 我认为您的插入命令名称是comma(注意末尾的“a”)而不是导致问题的comm。我也更新了答案。 comma.Parameters.AddWithValue("@uid", Session["uid"]); comma.Parameters.AddWithValue("@pid", lblAtC.Text); comma.Parameters.AddWithValue("@qty", 1); comma.Parameters.AddWithValue("@dtShopped", DateTime.Now.ToString()); int result = comma.ExecuteNonQuery();
    • 我试过了,但它在同一行给出了同样的错误
    猜你喜欢
    • 2019-07-26
    • 2019-05-22
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    相关资源
    最近更新 更多