如何从datalist更新数据库表?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从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();


                    }
                }
            }
        }
    }
}

答案

尝试像这样更新代码:

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块中以便将其处理掉。

以上是关于如何从datalist更新数据库表?的主要内容,如果未能解决你的问题,请参考以下文章

用datalist如何实现分页的代码(C#)

p:dataList没有更新

ASP.NET DataList嵌套实现评论效果

ASP.NET DataList嵌套实现评论效果

如何将数据从 BottomSheetDialogFragment 返回到父片段

将数据从底部工作表对话框片段传递到片段