【问题标题】:Can't figure out what's wrong when trying to update a database entry尝试更新数据库条目时无法弄清楚出了什么问题
【发布时间】:2013-12-16 22:52:07
【问题描述】:

我不明白为什么更新我的数据库条目不起作用。有时它告诉我存在语法错误,而其他时候当我尝试更新后尝试删除条目时,它告诉我连接未关闭。我对 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

【问题讨论】:

    标签: sql vb.net winforms


    【解决方案1】:

    如果您的任何值包含撇号,您的语法将是错误的 - 您应该使用参数而不是连接 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 汇集并且创建起来很便宜。

    【讨论】:

    • 参数优于将变量连接到查询中;但我个人认为存储过程更可取。
    猜你喜欢
    • 1970-01-01
    • 2018-05-09
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多