2012-08-27 79 views
0

我需要幫助搞清楚我的SQL語句中的錯誤。我一直在嘗試幾件事情,但似乎沒有任何工作? 這是錯誤消息我收到SQL錯誤訪問2010年VBA更新命令

Run-time error '3075': 

Syntax error (missing operator) in query expression '([description] = Manufacturing and Delivery Schedule AND [pr_num] = 83)'. 

這是我的代碼:

Private Sub Command6_Click() 
' =================================================== 
' Receives the selected item in the combo box 
' =================================================== 

' Open the Database connection 
Dim data_base As Database 
Set data_base = CurrentDb 

' Grab description and pr number from the form 
Dim desc As string 
dim pr_number as long 
desc = Combo4.Value 
pr_number = Text8.Value 

' Build the query 
Dim query As String 
query = "UPDATE VDR_Table " & _ 
    "SET [received] = [p1] " & _ 
    "WHERE ([description] = " & desc & _ 
    " AND [pr_num] = " & pr_number & ");" 

Dim rec_set As DAO.Recordset 
Set rec_set = data_base.OpenRecordset(query) 

' Build the QueryDef 
Set qd = data_base.CreateQueryDef("") 
qd.SQL = query 

' Execute query 
qd.Parameters("p1").Value = true 
qd.Execute 

' Close nad null record set 
rec_set.close 
set rec_set = nothing 

' Close the connection to the database 
data_base.Close 

' Prompt the user success 
MsgBox "Item has been received" 
End Sub 

提前任何幫助謝謝!

回答

1

由於它是一個字符串字段,因此您需要將描述字段值用引號括起來。它應該看起來像這樣:

' Build the query 
Dim query As String 
query = "UPDATE VDR_Table " & _ 
    "SET [received] = [p1] " & _ 
    "WHERE ([description] = '" & desc & _ 
    "' AND [pr_num] = " & pr_number & ");" 

刪除以下鏈接,因爲它們在這種情況下無關緊要。

此外,我會建議使用參數,而不是字符串連接,以避免SQL注入。以下是使用VBA參數的示例 - http://support.microsoft.com/kb/181734 - 以下是爲什麼要使用參數化的sql - http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html的一些推理。

+0

您將遇到DAO,參數和一個很長的字符串的困難。 SQL注入在MS Access中不完全相同。我傾向於在desc中避開任何可能的單引號。 – Fionnuala

+0

轉義報價確定,但如果他使用參數不會照顧這個問題? – ryanulit

+0

您不能使用帶有DAO和超過255的字符串的參數。 – Fionnuala