尝试更新访问数据库时,UPDATE语句失败 - VB.Net

时间:2013-01-08 19:50:46

标签: vb.net ms-access

我正在尝试使用VB.Net前端和Access 2003后端为自己创建一个简单的票务软件。我允许添加新行,但是当我尝试编写更新行button时,它会给出错误Microsoft JET Database Engine - Syntax error in UPDATE statement.我无法找到问题所在。

Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
    Dim da As New OleDbDataAdapter
    Dim dt As New DataTable
    Dim ConnectString As String = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\aaron-pister\Desktop\New Role Notes\Issue Tracker Express\Issue Tracker Express\Issue Tracker.mdb")
    Dim con As New OleDbConnection(ConnectString)
    con.Open()
    Dim Green42 As String = "UPDATE Issues Basic Details SET [Company Name] = '" & txtClientName.Text & "', [Status] = '" & cbStatus.Text & "', [Company Contact] = '" & txtClientContact.Text & "', [Description] = '" & txtDesc.Text & "', [Notes] = '" & txtRes.Text & "' WHERE [TicketNum] = '" & txtTicket.Text & "'"
    'con.Open()
    If txtClientName.Text <> "" Then
        Try
            'MyCom.CommandText = "UPDATE [Issues Basic Details] SET Company Name = '" & txtClientName.Text & "', Status = '" & cbStatus.Text & "', Company Contact = '" & txtClientContact.Text & "', Description = '" & txtDesc.Text & "', Notes = '" & txtRes.Text & "' WHERE TicketNum = '" & txtTicket.Text & "')"
            da = New OleDbDataAdapter(Green42.ToString, ConnectString)
            da.Fill(dt)
            da.Update(EsInfo1, "Issues Basic Details")
            MsgBox("Your record has been updated successfully.", MsgBoxStyle.DefaultButton1, "New Ticket Submitted")
        Catch ex As Exception
            MsgBox(ex.Source & "-" & ex.Message)
            con.Close()
            Exit Sub
        End Try
    Else
        MsgBox("You must have an entry in the Client Name, Client Contact and Status fields. It is recommended to also have a value in the Description field.", MsgBoxStyle.OkOnly, "Issue Tracker Express")
        btnNewIncident_Click(sender, e)
        Exit Sub
    End If
End Sub

3 个答案:

答案 0 :(得分:4)

您的桌名也必须加上括号:

Dim Green42 As String = "UPDATE [Issues Basic Details] SET [Company Name]..."

此外,use parameters而不是将值放入字符串中。它避免了SQL注入。

答案 1 :(得分:0)

此:

UPDATE Issues Basic Details SET ...

是无效的SQL。您需要通过限定表名来帮助它:

UPDATE [Issues Basic Details] SET ...

其他一些建议:

  1. 使用预准备语句(参数化SQL以避免SQL注入攻击)
  2. 不要在click事件处理程序中定义这种类型的行为 - 有一个帮助程序类来执行此操作,因此可以重复使用它,而不是直接耦合到UI。
  3. 使用Using语句。您的OleDbConnection班级实施IDisposable。您没有正确处理此连接。

答案 2 :(得分:0)

虽然目前很难阅读您的代码,但看起来您似乎正在尝试执行“AdHoc”查询,这可能会导致很多问题。

我建议您先将语句更改为parameterized query以帮助诊断问题。