Do we have transactions in MS-Access?

前端 未结 3 1960
野性不改
野性不改 2020-11-29 08:25

I am developing a small desktop application using C#.NET and MS-Access. I don\'t have any prior experience of MS-Access. I want to know if we can use transa

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 08:58

    Nobody has actually given you any code examples here in the answer or even cited an example (the Access help files do include examples, though). The key issue to keep in mind is that in Jet/ACE (Access does not support transactions itself -- it depends on whatever database engine you're using for that) that the transaction is controlled at the workspace level. You can create a new workspace for your transaction or create a new one. Here's some sample code:

      On Error GoTo errHandler
        Dim wrk As DAO.Workspace
        Dim db As DAO.Database
        Dim lngInvoiceID As Long
    
        Set wrk = DBEngine.Workspaces(0)
        Set db = wrk.OpenDatabase(CurrentDb.Name)
        With wrk
          .BeginTrans
          db.Execute "INSERT INTO tblInvoice (CustomerID) VALUES (123);", dbFailOnError
          lngInvoiceID = db.OpenRecordset("SELECT @@IDENTITY")(0)
          db.Execute "INSERT INTO tblInvoiceDetail (InvoiceID) VALUES (" & lngInvoiceID & ")", dbFailOnError
          .CommitTrans
          Debug.Print "Inserted Invoice header and detail for Invoice " & lngInvoiceID
        End With
    
      exitRoutine:
        If Not (db Is Nothing) Then
           db.Close
           Set db = Nothing
        End If
        Set wrk = Nothing
        Exit Sub
    
      errHandler:
        MsgBox Err.Number & ": " & Err.Description, vbExclamation, "Error in transaction"
        wrk.Rollback
        Resume exitRoutine
    

    (code tested and working within Access)

提交回复
热议问题