MS access 运行 SQL 没有插入数据,没有报错

MS access running SQL doesn't insert data, no error

我想从表单向此 table 添加数据。

我有工作和团队 ID 的组合框,可以从它们各自的 table 中查找数据。

Private Sub save_new_Click()
On Error GoTo save_new_Click_Err

    On Error Resume Next
    Dim strSQL As String

    strSQL = "INSERT INTO Employee (Name,ATUUID,Job ID,Team ID,Start Date, Comments) " & _
     " VALUES(" & Me.Employye_Name & ", " & Me.ATTUID & ", " & Me.cboFunc & ", " & _
     Me.cboTeam & ", " & Me.Start_Date & ", " & Me.Comments & ")"
     Debug.Print strSQL
    With CurrentDb
        .Execute (strSQL), dbFailOnError
        Debug.Print .RecordsAffected
    End With

这是生成的 SQL 字符串:

 INSERT INTO Employee (Name,ATUUID,Job ID,Team ID,Start Date, Comments)  VALUES(asd, asd, 1, 2, 7/10/2015, asdasd)

Debug.Print.RecordsAffected

打印 0

一样,您没有看到错误的原因是 On Error Resume Next 隐藏了错误。当你使用它时,你告诉 Access "ignore any error --- don't even mention it --- and continue at the next line."

但是代码构建的INSERT语句肯定会触发错误。如果从即时 window 复制 Debug.Print strSQL 的输出,您可以确认这一事实,在查询设计器中创建一个新查询,将查询切换到 SQL 视图,粘贴语句文本并尝试 运行 它。

当您的字段名称包含 space 时,您必须将其括在方括号中,以便数据库引擎将其识别为一个标识符而不是两个。我还将 Name 括起来,因为它是一个保留字,但我怀疑它是否真的会导致这里的问题:

"INSERT INTO Employee ([Name], ATUUID, [Job ID], [Team ID], [Start Date], Comments)"

除此之外,我建议您使用基于参数查询的临时 QueryDef,提供参数值,然后 Execute 它。

'On Error Resume Next '<-- leave this disabled, AT LEAST while debugging!
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String

strSQL = "INSERT INTO Employee ([Name], ATUUID, [Job ID], [Team ID], [Start Date], Comments)" & vbCrLf & _
    "VALUES (pName, pATUUID, pJobID, pTeamID, pStartDate, pComments);"
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strSQL)
With qdf
    .Parameters("pName").Value = Me.Employye_Name.Value
    .Parameters("pATUUID").Value = Me.ATTUID.Value
    .Parameters("pJobID").Value = Me.cboFunc.Value
    .Parameters("pTeamID").Value = Me.cboTeam.Value
    .Parameters("pStartDate").Value = Me.Start_Date.Value
    .Parameters("pComments").Value = Me.Comments.Value
    .Execute dbFailOnError
End With
Debug.Print db.RecordsAffected