2017-09-08 115 views
0

將數據插入數據庫時​​遇到一些問題。 我正在使用mssql。vba access mssql插入數據

Private Sub EditMethodAdd_Click() 

Dim rs As ADODB.Recordset 
Dim introw 
Dim strState As String 
Dim strsql1 As String 
Dim strsql2 As String 
Dim all As String 

Dim strConn As String 
Dim conn As ADODB.Connection 

MsgBox ("EditM1.Value:" & EditM1.value) 


strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;" 

strsql1 = " INSERT INTO dbo.Method(MethodID, MethodClass, Category, Description, Description2, MSA, ReqType, Equipment, Location, Spec1, Spec2, Spec3, Spec4, Spec5, Spec6, PilotingYN) " 
strsql2 = " VALUES(EditM1.value, 'Piloting', EditM3.value, Null, Null, Null, Null, EditM2.value, EditM4.value, EditM5.value, EditM6.value, EditM7.value, EditM8.value, EditM9.value, EditM10.value, Null)" 


all = strsql1 & strsql2 

MsgBox ("ALL" & all) 


Set conn = New ADODB.Connection 
conn.Open strConn 

Set rs = New ADODB.Recordset 
rs.Open all, conn 
MsgBox ("Insert Success") 

EditMethodList.Requery 

conn.Close 
Set rs = Nothing 
Set conn = Nothing 

MsgBox "Data has been updated" 
EditMethodList.Requery 

End Sub 

當我使用MSGBOX檢查EditM1值,它顯示正確。 但我得到這樣的錯誤消息。 enter image description here

有沒有人可以解決這個問題? 預先感謝您。

回答

2

你把字面值「EditM1.value」到SQL:你應該改爲發送控制的價值:

strsql2 = " VALUES(" & EditM1.value & ", 'Piloting', " & _ 
         EditM3.value & ", Null,..." 'etc 

如果任何值被送進是不是數字,然後他們應該用單引號包裝。

+0

你能給我完整的代碼嗎?因爲我一直在收到錯誤....對不起... –

+0

@ yowe3k - 已修復,謝謝 –

2

刪除線:

strsql1 = ... 
strsql2 = ... 

all = strsql1 & strsql2 

,寫這個代替

all = "INSERT INTO dbo.Method(MethodID, MethodClass, Category, Description, Description2, MSA, ReqType, Equipment, Location, Spec1, Spec2, Spec3, Spec4, Spec5, Spec6, PilotingYN) " 
all = all & "VALUES(" & EditM1.value & ", 'Piloting'," & EditM3.value & ", Null, Null, Null, Null," & EditM2.value & "," & EditM4.value & "," 
all = all & EditM5.value & "," & EditM6.value & "," & EditM7.value & "," & EditM8.value & "," & EditM9.value & "," & EditM10.value & ", Null)" 

如果插入EditM1.value到雙引號,像你一樣,VBA讀取它作爲一個字符串,它不是指它的價值。您需要連接字符串和值與&來創建您的查詢。

+0

它不工作...它顯示'錯誤的語法附近..... –

+2

不要這樣做。使用參數查詢,這裏是一個解釋和示例:https://stackoverflow.com/a/46057683/3820271 – Andre