INSERT INTO语句中的语法错误

时间:2014-04-08 14:40:51

标签: vb.net ms-access

我在几天内遇到以下错误,无法找到错误。谁能帮助我解决这个问题,最好用解决方案重新编写代码。

Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
     Dim cmd As New OleDb.OleDbCommand
     If Not cnn.State = ConnectionState.Open Then
        'The line of code below opens the connection to the database if it isnt open
        cnn.Open()
     End If

    cmd.Connection = cnn
    'Check whether to add new or update
    If Me.txtItemID.Tag & "" = "" Then
        'Add new 
        'The line of coding below adds data to table
        cmd.CommandText = "INSERT INTO Product ([Item ID], [Item Name], [Item Type], [Quantity], [Min Shelf Stock], [Purchase Price], [Note]) " & _
                        " VALUES (" & Me.txtItemID.Text & ",'" & Me.txtItemName.Text & "','" & _
                        Me.cboItemType.Text & "','" & Me.txtQuantity.Text & "','" & _
                        Me.txtMinShelfStock.Text & "','" & Me.txtPurchasePrice.Text & "','" & _
                        Me.txtNote.Text & "')"
        cmd.ExecuteNonQuery()
    Else
        'Update data in the table 
        cmd.CommandText = "UPDATE Product " & _
                    " SET Item ID=" & Me.txtItemID.Text & _
                    ", Item Name='" & Me.txtItemName.Text & "'" & _
                    ", Item Type='" & Me.cboItemType.Text & "'" & _
                    ", Quantity='" & Me.txtQuantity.Text & "'" & _
                    ", Min Shelf Stock='" & Me.txtMinShelfStock.Text & "'" & _
                    ", Purchase Price='" & Me.txtPurchasePrice.Text & "'" & _
                    ", Note='" & Me.txtNote.Text & "'" & _
                    " WHERE Item ID=" & Me.txtItemID.Tag
        cmd.ExecuteNonQuery()
    End If
    'Refresh data in list
    RefreshData()
    'Clear the form
    Me.btnClear.PerformClick()

    'The code below closes the connection to the database
    cnn.Close()
End Sub

2 个答案:

答案 0 :(得分:2)

试试这个...

cmd.CommandText = "INSERT INTO Product ([Item Id], [Item Name], [Item Type], [Quantity], [Min  Shelf Stock], [Purchase Price], [Note]) VALUES (@id, @name, @iType, @quantity, @minshelfstock, @price, @note)"
cmd.Paramaters.AddWithValue("@id", txtItemId.Text)
cmd.Paramaters.AddWithValue("@name", txtItemName.Text)
cmd.Paramaters.AddWithValue("@iType", cboItemType.Text)
cmd.Paramaters.AddWithValue("@quantity", txtQuantity.Text)
cmd.Paramaters.AddWithValue("@minshelfstock", txtMinShelfStock.Text)
cmd.Paramaters.AddWithValue("@price", txtPurchasePrice.Text)
cmd.Paramaters.AddWithValue("@note", txtNote.Text)

希望这有帮助

RoDiT

答案 1 :(得分:0)

我注意到的第一件事是您的数量,价格和最小货架库存在您的选择语句中用引号括起来,如,'" & Me.txtQuantity.Text & "',,它们会将它们作为文本提交,但如果表中的这些字段是数字格式某种类型,然后必须输入数字," & Me.txtQuantity.Text & ",