0

有谁能够帮我?为什么我会收到此错误?

如果我从 prod_id 中删除仅留下数字的“P”,它可以工作,但如果我添加字母,它会显示“列名无效”。

我已经添加.ToString()了,但是为什么它仍然不能接受 varchar 而只能接受 int。

这是错误

这是我的代码

public partial class AddtoCart : System.Web.UI.Page
{
    SqlConnection conn = new SqlConnection(Global.cs);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["Username"] == null)
            {
                Response.Redirect("Authentication.aspx");
            }

            // Adding product to Gridview
            Session["addproduct"] = "false";
            DataTable dt = new DataTable();

            DataRow dr;
            dt.Columns.Add("sno");
            dt.Columns.Add("Id");
            dt.Columns.Add("Pname");
            dt.Columns.Add("Pimage");
            dt.Columns.Add("Pprice");
            dt.Columns.Add("Pquantity");
            dt.Columns.Add("Ptotal");

            if (Request.QueryString["Id"] != null)
            {
                if (Session["buyitems"] == null)
                {
                    dr = dt.NewRow();
                    SqlConnection conn = new SqlConnection(Global.cs);

                    SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["Id"] , conn);
                    DataSet ds = new DataSet();
                    da.Fill(ds);

                    dr["sno"] = 1;
                    dr["Id"] = ds.Tables[0].Rows[0]["prod_id"].ToString();
                    dr["Pname"] = ds.Tables[0].Rows[0]["prod_name"].ToString();
                    dr["Pimage"] = ds.Tables[0].Rows[0]["prod_img"].ToString();
                    dr["Pprice"] = ds.Tables[0].Rows[0]["prod_price"].ToString();
                    dr["Pquantity"] = Request.QueryString["quantity"];

                    int price = Convert.ToInt32(ds.Tables[0].Rows[0]["prod_price"].ToString());
                    int Quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
                    int TotalPrice = price * Quantity;
                    dr["Ptotal"] = TotalPrice;

                    dt.Rows.Add(dr);

                    conn.Open();
                    SqlCommand cmd = new SqlCommand("insert into Cart values('" + dr["sno"] + "','" + dr["Id"] + "','" + dr["Pname"] + "','" + dr["Pimage"] + "','" + dr["Pprice"] + "','" + dr["Pquantity"] + "','" + dr["Ptotal"] + "','" + Session["Username"].ToString() + "')", conn);
                    cmd.ExecuteNonQuery();
                    conn.Close();

                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                    Session["buyitems"] = dt;
                    Button1.Enabled = true;

                    GridView1.FooterRow.Cells[5].Text = "Total Amount";
                    GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
                    Response.Redirect("AddtoCart.aspx");
                }
                else
                {
                    dt = (DataTable)Session["buyitems"];
                    int sr;
                    sr = dt.Rows.Count;

                    dr = dt.NewRow();
                    SqlConnection conn = new SqlConnection(Global.cs);

                    SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["id"], conn);
                    DataSet ds = new DataSet();
                    da.Fill(ds);

                    dr["sno"] = sr + 1;
                    dr["Id"] = ds.Tables[0].Rows[0]["prod_id"].ToString();
                    dr["Pname"] = ds.Tables[0].Rows[0]["prod_name"].ToString();
                    dr["Pimage"] = ds.Tables[0].Rows[0]["prod_img"].ToString();
                    dr["Pprice"] = ds.Tables[0].Rows[0]["prod_price"].ToString();
                    dr["Pquantity"] = Request.QueryString["quantity"];

                    int price = Convert.ToInt32(ds.Tables[0].Rows[0]["prod_price"].ToString());
                    int Quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
                    int TotalPrice = price * Quantity;
                    dr["Ptotal"] = TotalPrice;

                    dt.Rows.Add(dr);

                    conn.Open();
                    SqlCommand cmd = new SqlCommand("insert into Cart values('" + dr["sno"] + "','" + dr["Id"] + "','" + dr["Pname"] + "','" + dr["Pimage"] + "','" + dr["Pprice"] + "','" + dr["Pquantity"] + "','" + dr["Ptotal"] + "','" + Session["Username"].ToString() + "')", conn);
                    cmd.ExecuteNonQuery();
                    conn.Close();

                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                    Session["buyitems"] = dt;
                    Button1.Enabled = true;

                    GridView1.FooterRow.Cells[5].Text = "Total Amount";
                    GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
                    Response.Redirect("AddtoCart.aspx");

                }
            }
            else
            {
                dt = (DataTable)Session["buyitems"];
                GridView1.DataSource = dt;
                GridView1.DataBind();

                if (GridView1.Rows.Count > 0)
                {
                    GridView1.FooterRow.Cells[5].Text = "Total Amount";
                    GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();

                }
            }
        }

        if (GridView1.Rows.Count.ToString() == "0")
        {
            Button3.Enabled = false;
            Button1.Enabled = false;
        }
        else
        {
            Button3.Enabled = true;
            Button1.Enabled = true;
        }

    }

    // 2.Calculating Final Price
    public int grandtotal()
    {
        DataTable dt = new DataTable();
        dt = (DataTable)Session["buyitems"];
        int nrow = dt.Rows.Count;
        int i = 0;
        int totalprice = 0;

        while (i < nrow)
        {
            totalprice = totalprice + Convert.ToInt32(dt.Rows[i]["Ptotal"].ToString());

            i = i + 1;
        }

        return totalprice;
    }

    // 4. Deleting Row From Cart
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        DataTable dt = new DataTable();
        dt = (DataTable)Session["buyitems"];

        for (int i = 0; i <= dt.Rows.Count - 1; i++)
        {
            int sr;
            int sr1;
            string qdata;
            string dtdata;
            sr = Convert.ToInt32(dt.Rows[i]["sno"].ToString());
            TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];
            qdata = cell.Text;
            dtdata = sr.ToString();
            sr1 = Convert.ToInt32(qdata);
            TableCell prID = GridView1.Rows[e.RowIndex].Cells[1];

            if (sr == sr1)
            {
                dt.Rows[i].Delete();
                dt.AcceptChanges();

                conn.Open();
                SqlCommand cmd = new SqlCommand("Delete top (1) from Cart where product_id='" + prID.Text + "' and username= '" + Session["username"] + "' ", conn);
                cmd.ExecuteNonQuery();
                conn.Close();
                //Item Has Been Deleted From Shopping Cart
                break;
            }
        }

        // 5. Setting SNo. after deleting Row item from cart
        for (int i = 1; i <= dt.Rows.Count; i++)
        {
            dt.Rows[i - 1]["sno"] = i;
            dt.AcceptChanges();
        }

        Session["buyitems"] = dt;
        Response.Redirect("AddtoCart.aspx");
    }

    // 6. Button Click
    protected void Button1_Click(object sender, EventArgs e)
    {
        bool isTrue = false;
        DataTable dt = (DataTable)Session["buyitems"];

        for (int i = 0; i <= dt.Rows.Count - 1; i++)
        {
            //SqlConnection conn = new SqlConnection(Global.cs);
            //conn.Open();
            //SqlCommand cmd = new SqlCommand("insert into Cart(sno,product_id,product_name,product_price,product_quantity,username) values('" + dt.Rows[i]["sno"] + "','" + dt.Rows[i]["Id"] + "','" + dt.Rows[i]["Pname"] + "','" + dt.Rows[i]["Pprice"] + "','" + dt.Rows[i]["Pquantity"] + "','" + Session["Username"] + "')", conn);
            //cmd.ExecuteNonQuery();
            //conn.Close();

            int pId = Convert.ToInt16(dt.Rows[i]["Id"]);
            int pQuantity = Convert.ToInt16(dt.Rows[i]["Pquantity"]);
            SqlDataAdapter sda = new SqlDataAdapter("Select stock_count, prod_name from Product2 where prod_id='" + pId + "' ", conn);
            DataTable dtble = new DataTable();
            sda.Fill(dtble);
            int quantity = Convert.ToInt16(dtble.Rows[0][0]);

            if(quantity == 0)
            {
                string pName = dtble.Rows[0][1].ToString();
                string msg = "" + pName + " is not in Stock";
                Response.Write("<script>alert('" + msg + "');</script>");
                isTrue = false;
            }
        }

        if (GridView1.Rows.Count.ToString() == "0")
        {
            Response.Write("<script>alert('Your Cart is Empty. You cannot place an Order');</script>");
        }
        else
        {
            if (isTrue == true)
            {
                Response.Redirect("Checkout2.aspx");
            }
        }

        // If Session is Null Redirecting to login else Placing the order
        if (Session["Username"] == null)
        {
            Response.Redirect("Authentication.aspx");
        }
        else
        {
            Response.Redirect("Checkout2.aspx");
        }
    }

    public void clearCart()
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("Delete from Cart where username='" + Session["Username"] + "' ", conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        Response.Redirect("AddtoCart.aspx");
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        Session["buyitems"] = null;
        clearCart();
    }
}

这是数据库表

CREATE TABLE [dbo].[Product2] 
(
    [prod_id]      VARCHAR(6)    NOT NULL,
    [prod_name]    VARCHAR(50)   NOT NULL,
    [prod_price]   FLOAT(53)     NOT NULL,
    [prod_desc]    VARCHAR(120)  NOT NULL,
    [prod_img]     NVARCHAR(MAX) NOT NULL,
    [prod_cat]     VARCHAR(6)    NOT NULL,
    [stock_count]  INT           NULL,
    [weight]       DECIMAL(9, 2) NULL,
    [width]        DECIMAL(9, 2) NULL,
    [length]       DECIMAL(9, 2) NULL,
    [height]       DECIMAL(9, 2) NULL,
    [shipping_fee] DECIMAL(9, 2) NOT NULL,
    [created_at]   DATETIME      NOT NULL,
    [updated_at]   DATETIME      NULL,
    [prod_status]  NVARCHAR(MAX) NULL,

    PRIMARY KEY CLUSTERED ([prod_id] ASC),
    CONSTRAINT [FK_Product2_ToTable] 
        FOREIGN KEY ([prod_cat]) REFERENCES [dbo].[Category] ([cat_id])
);

这是表的数据

4

1 回答 1

2

您传递查询的方式可能会导致SQL 注入

SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["Id"] , conn);

我希望您要实现的最终查询是

select * from Product2 where prod_id=`P100`

但是,如果您在查询中与“P”连接,则在修改代码后,您将获得:

select * from Product2 where prod_id=P100

这将返回结果:

列名“P100”无效

将字符串连接到查询中很危险,可能会破坏您的查询。

您需要创建一个SqlCommand变量并将其传递给SqlDataAdapter. 并且还用于SqlParameter传递参数值。

SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = @Prod_ID", con);
cmd.Parameters.Add("@Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;

创建并初始化 SqlCommand 后,将其传递给 SqlDataAdpater,如下所示

SqlDataAdapter da = new SqlDataAdapter(cmd);

附加建议:

  1. 使用usingblock SqlConnection,因为这些SqlCommandSqlDataAdapter使用 IDisposable 接口实现)将在进程结束或触发异常后自动释放资源。
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(Global.cs))
{
    using (SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = @Prod_ID", con))
    {
        cmd.Parameters.Add("@Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;

        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
            da.Fill(ds);
        }
    }
}

更新的答案归功于@Tim Schmelter 的建议

对于C#8.0 中的 Using 声明,您不需要为 using 块添加范围。

using 声明是一个以 using 关键字开头的变量声明。它告诉编译器被声明的变量应该放在封闭范围的末尾。

DataSet ds = new DataSet();

using SqlConnection conn = new SqlConnection(Global.cs);

using SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = @Prod_ID", con);
cmd.Parameters.Add("@Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;

using SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
于 2021-04-17T06:53:54.950 回答