2013-12-16 37 views
-1

我找不出爲什麼更新我的數據庫條目無法正常工作。有時它會告訴我存在語法錯誤,而在嘗試更新後嘗試刪除條目的其他時候,它會告訴我連接未關閉。我不熟悉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 

回答

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並且創建起來很便宜。

+0

參數優於將變量連接到查詢中;但我個人認爲存儲過程更加可取。 –

相關問題