2012-08-09 116 views
3

遇到了插入sql的問題。下面的所有代碼都可以工作,例外的是爲level添加值的SQL字符串。這是我的onclick代碼,帶有三個框的表單。存儲pH,Temp和Level值的表格具有爲所有三個字段設置字段大小「單個」的數字格式。訪問INSERT INTO SQL錯誤

再一次,如果我把'水平'框留空,它就可以工作!但是,當我試圖插入一個級別值,與任何其他值的組合,它失敗。

下面的代碼:

Private Sub SubmitSampleData_Click() 
Dim pH, Temp, Level As Single 
Dim TodaysDate As Date 

TodaysDate = Date 

If IsNull(Me.pH.Value) Then 
    pH = 1 
Else 
    pH = Me.pH.Value 
End If 
If IsNull(Me.Temp.Value) Then 
    Temp = 1 
Else 
    Temp = Me.Temp.Value 
End If 
If IsNull(Me.Level.Value) Then 
    Level = 1 
Else 
Level = Me.Level.Value 
End If 

If Level = 1 And Temp = 1 And pH = 1 Then 
    Exit sub 
ElseIf Level = 1 And Temp = 1 Then 
    CurrentDb.Execute "INSERT INTO SampleDataQuery (DateCreated, pH) VALUES (#" & TodaysDate & "#, " & pH & ")" 
ElseIf Temp = 1 And pH = 1 Then 
    CurrentDb.Execute "INSERT INTO SampleDataQuery (DateCreated, Level) VALUES (#" & TodaysDate & "#, " & Level & ")" 
ElseIf Level = 1 And pH = 1 Then 
    CurrentDb.Execute "INSERT INTO SampleDataQuery (DateCreated, Temp) VALUES (#" & TodaysDate & "#, " & Temp & ")" 
ElseIf Level = 1 Then 
    CurrentDb.Execute "INSERT INTO SampleDataQuery (DateCreated, pH, Temp) VALUES (#" & TodaysDate & "#, " & pH & ", " & Temp & ")" 
ElseIf Temp = 1 Then 
    CurrentDb.Execute "INSERT INTO SampleDataQuery (DateCreated, pH, Level) VALUES (#" & TodaysDate & "#, " & pH & ", " & Level & ")" 
ElseIf pH = 1 Then 
    CurrentDb.Execute "INSERT INTO SampleDataQuery (DateCreated, Temp, Level) VALUES (#" & TodaysDate & "#, " & Temp & ", " & Level & ")" 
Else  
    CurrentDb.Execute "INSERT INTO SampleDataQuery (DateCreated, pH, Temp, Level) VALUES (#" & TodaysDate & "#, " & pH & ", " & Temp & ", " & Level & ")" 
End If 

MsgBox "Submit Successful!", vbOKOnly, "Success!" 

Me.pH.Value = Null 
Me.Temp.Value = Null 
Me.Level.Value = Null 
End Sub 
+3

你爲什麼不使用參數化查詢? – RedFilter 2012-08-09 15:42:36

+0

忽略不使用參數化查詢,數據庫中Level的數據類型是什麼? – Ghost 2012-08-09 15:44:11

+0

級別的數據類型是大小單一的數字 – riley3131 2012-08-09 15:44:40

回答

4

水平是一個保留字,必須用方括號括起來。

CurrentDb.Execute "INSERT INTO SampleDataQuery (DateCreated, [Level]) VALUES (#" _ 
    & TodaysDate & "#, " & Level & ")" 

保留字

Jet
ACE

+1

或者,字段名稱可以更改爲其他內容,如「lvl」 – PowerUser 2012-08-09 15:53:40

+0

非常感謝!這工作完美!我不知道Level是保留的,我會立即改變它!哇!!不知道哪裏可以找到所有保留字的列表。再次感謝!! – riley3131 2012-08-09 15:54:45

+0

@PowerUser有一條規定,不要使用縮寫,所以pHLevel會更好。我不知道爲什麼要給lvl一個建議。 – Fionnuala 2012-08-09 15:54:50