我尝试使用For...Next
在我的数据库中保存购物车行。可以保存数据,但数据重复。
例如,我的购物车中只有两个产品,但保存了三件重复数据。
Dim x As Int16
Dim txtProductID As Label
Dim txtProductName As Label
Dim txtCategory As Label
Dim lblPrice As Label
Dim txtQuantity As TextBox
Dim lblTotalPrice As Label
For x = 0 To GridView2.Rows.Count - 1
txtProductID = DirectCast(GridView2.Rows(x).FindControl("lblProductID"), Label)
txtProductName = DirectCast(GridView2.Rows(x).FindControl("lblProductName"), Label)
txtCategory = DirectCast(GridView2.Rows(x).FindControl("lblProductCategory"), Label)
lblPrice = DirectCast(GridView2.Rows(x).FindControl("lblProductPrice"), Label)
txtQuantity = DirectCast(GridView2.Rows(x).FindControl("txtProductQuantity"), TextBox)
lblTotalPrice = DirectCast(GridView2.Rows(x).FindControl("lblTotalPrice"), Label)
query &= "INSERT INTO PRODUCT2 (Prod_ID, Unit_Price, Quantity, Total_Price, Prod_Name, Prod_Category) "
query &= "VALUES (@Prod_ID, @Unit_Price, @Quantity, @Total_Price, @Prod_Name, @Prod_Category)"
Using conn As New SqlConnection("Server=MEIYI-PC;Initial Catalog=VBTrading;Integrated Security=True")
Using comm As New SqlCommand()
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("@Prod_ID", txtProductID.Text)
.Parameters.AddWithValue("@Unit_Price", txtProductName.Text)
.Parameters.AddWithValue("@Quantity", txtCategory.Text)
.Parameters.AddWithValue("@Total_Price", lblPrice.Text)
.Parameters.AddWithValue("@Prod_Name", txtQuantity.Text)
.Parameters.AddWithValue("@Prod_Category", lblTotalPrice.Text)
End With
Try
conn.Open()
comm.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using
Next
下面是数据库和表的图像。
答案 0 :(得分:0)
变化:
query& =" INSERT INTO PRODUCT2(Prod_ID,Unit_Price,Quantity,Total_Price,Prod_Name,Prod_Category)"
要:
query =" INSERT INTO PRODUCT2(Prod_ID,Unit_Price,Quantity,Total_Price,Prod_Name,Prod_Category)"
没有&。