将数据插入数据库时遇到问题。 我正在使用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的值时,它显示正确。 但是我得到了这样的错误信息。
有没有人可以解决这个问题? 提前谢谢。
答案 0 :(得分:2)
您将文字值“EditM1.value”放入SQL:您应该发送控件的值:
strsql2 = " VALUES(" & EditM1.value & ", 'Piloting', " & _
EditM3.value & ", Null,..." 'etc
如果发送的任何值不是数字,那么它们应该用单引号括起来。
答案 1 :(得分: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将其作为字符串读取,并且不会引用其值。您需要将字符串和值与&连接起来。创建您的查询。