尝试更新数据库条目时无法弄清楚出了什么问题

时间:2013-12-16 22:52:08

标签: sql vb.net winforms

我无法弄清楚为什么更新我的数据库条目不起作用。有时它告诉我有一个语法错误,有时当我尝试删除一个条目后尝试更新它告诉我连接没有关闭。我不熟悉SQL,所以任何帮助都会受到赞赏。

Public Shared Property filename As String
Private dbConnection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=IT_Checkout.accdb")
Private dbAdapter As OleDbDataAdapter
Private dbDataset As DataSet

Public Function deleteReport(ByVal rID As String,
                               ByRef msg As String) As Boolean
    Dim sql As String
    sql = "DELETE FROM Reports WHERE RID = '" & rID & "'"
    If do_command(sql, msg) = False Then
        Return False
    End If

    If File.Exists(My.Application.Info.DirectoryPath & "\reports\" & rID & ".dat") Then
        My.Computer.FileSystem.DeleteFile(My.Application.Info.DirectoryPath & "\reports\" & rID & ".dat")
    End If

    Return True
End Function

Public Function updateReport(ByVal r As Report,
                             ByRef msg As String) As Boolean
    Dim sql As String = "UPDATE Reports SET Name='" & r.name & "', Date='" & r.outDate & "', Notes='" & r.notes & "', Archived='" & r.archived.ToString & "' WHERE RID='" & r.getID & "'"

    Return do_command(sql, msg)
End Function

Public Function do_command(ByVal sql As String,
                           ByRef msg As String) As Boolean
    Dim command As OleDbCommand
    Try
        dbConnection.Open()
        command = New OleDbCommand(sql, dbConnection)
        command.ExecuteNonQuery()
        dbConnection.Close()
        Return True
    Catch ex As Exception
        msg = "From Command: " & ex.Message
        Return False
    End Try
End Function

1 个答案:

答案 0 :(得分:3)

如果你的任何值包含撇号,你的语法就会出错 - 你应该使用参数而不是连接SQL:

Dim sql As String = "UPDATE Reports SET [Name]=?, [Date]=?, Notes=?, Archived=? WHERE RID=?"

command = New OleDbCommand(sql, dbConnection)

command.Parameters.Add("Name").Value = r.name
command.Parameters.Add("Date").Value = r.outDate
command.Parameters.Add("Notes").Value = r.notes
command.Parameters.Add("Archived").Value = r.archived
command.Parameters.Add("RID").Value = r.getID

command.ExecuteNonQuery()
dbConnection.Close()

您也不应该共享一个连接对象 - 连接由.NET汇集并且创建起来很便宜。