如何从数据列表更新数据库表?

时间:2019-03-31 14:19:19

标签: c# asp.net database datalist

我正在建立一个电子商务网站,并且使用数据列表显示我的产品,当我按下“添加到购物车”按钮时,应该将它们添加到数据库表中,但是由于某种原因,这些产品在数据库表中未更新。另外,单击第一个产品将显示一条错误消息,指出“已经有一个开放的阅读器”,并且显示错误的行是“ 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();


                    }
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试像这样更新代码:

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块中以将其丢弃。