Daily Backup of BE Database (4 Viewers)

Pete490h

Member
Local time
Today, 13:15
Joined
Jan 18, 2021
Messages
58
Just wondering if anyone has created a routine that carries out a daily backup of the backend database to cover each weekday
So on this Tuesday it backs up database_be.accdb to databaseTue_be.accdb, then overwrites next week etc
 
for automatic backup whenever the front-end is closed, you will need a startup, hidden form that when closed will
do the backup.
copy this to a module:
Code:
Function IsBackendInUse() As Boolean
    Dim strBackendPath As String
    Dim intFileNum As Integer
    
    strBackendPath = BackEndPath()
    
    On Error Resume Next
    intFileNum = FreeFile
    Open strBackendPath For Binary Access Read Lock Read Write As #intFileNum
    Close #intFileNum
    
    If Err.Number <> 0 Then
        IsBackendInUse = True  ' File is locked
    Else
        IsBackendInUse = False ' File is available
    End If
    On Error GoTo 0
End Function

Public Sub BackupBackendDatabase()
    Dim strSourcePath As String
    Dim strBackupPath As String
    Dim strBackupFileName As String
    
    ' change this to the correct path to your backup folder
    strBackupPath = Environ("userprofile") & "\documents\backup\"
    
    ' Path to your backend database
    strSourcePath = BackEndPath()
    
    ' Backup location with timestamp
    'strBackupFileName = GetBaseName(strSourcePath) & "_" & Format(Now(), "yyyy-mm-dd_hhnnss") & "." & GetExtension(strSourcePath)
    Dim strBaseName As String
    strBaseName = GetBaseName(strSourcePath)
    If Right(strBaseName, 3) = "_be" Then
        strBackupFileName = Left$(strBaseName, Len(strBaseName) - 3) & Format$(Date, "mmm") & "_be"
    Else
        strBackupFileName = GetBaseName(strSourcePath) & Format$(Date, "ddd")
    End If
    strBackupFileName = strBackupFileName & "." & GetExtension(strSourcePath)
    
    
    ' Create backup folder if it doesn't exist
    If Dir(strBackupPath, vbDirectory) = "" Then
        MkDir strBackupPath
    End If
    strBackupPath = strBackupPath & strBackupFileName
    
    ' Copy the backend database
    On Error Resume Next
    FileCopy strSourcePath, strBackupPath
    
    If Err.Number = 0 Then
        MsgBox "Backup created successfully: " & strBackupFileName, vbInformation
    Else
        MsgBox "Backup failed: " & Err.Description, vbExclamation
    End If
    On Error GoTo 0
End Sub


Public Function BackEndPath$()
Const conString = ";DATABASE="
Dim td As DAO.TableDef
Dim db As DAO.Database: Set db = CurrentDb
Dim conn$
For Each td In db.TableDefs
    conn = td.Connect
    If Len(conn) <> 0 Then
        If InStr(1, conn, conString) = 1 Then
            BackEndPath = Mid$(conn, Len(conString) + 1)
            Exit For
        End If
    End If
Next
Set td = Nothing: Set db = Nothing
End Function


' helper
Function GetFileName(strPath As String) As String
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetFileName = fso.GetFileName(strPath)
    Set fso = Nothing
End Function

Function GetExtension(strPath As String) As String
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetExtension = fso.GetExtensionName(strPath)
    Set fso = Nothing
End Function

Function GetBaseName(strPath As String) As String
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetBaseName = fso.GetBaseName(strPath)  ' Filename without extension
    Set fso = Nothing
End Function

now add code to the Close Event of your hidden, start-up form:
Code:
Private Sub Form_Close()
    If IsBackendInUse() Then
        MsgBox "Backup skipped - other users are currently accessing the database.", vbInformation
        Exit Sub
    End If

    Call BackupBackendDatabase
End Sub
 
I used to do this sort of task, albeit on a generation basis, rather than weekdays not using Access at all. I just used Windows Task scheduler to run a a Windows Script Host script which did the copy and replacing. This was, however, in the days before VBScript was denigrated, but it could easily be done in Javascript instead, or even using that monster Powershell. Mine used to run at 2 in the morning when nobody was using the DB.
 
Last edited:
Enable shadow copy and set the times you want the drive hosting the FE backed up. You can then use previous version to restore you FE to about any date. Now use at least Windows backup to do daily backups of that drive.
 
There is a massive issue in automated backup. If the database is open at the time of that backup operation, there is a VERY STRONG possibility that a backup taken at that moment will be unusable. The problem is not unique to Access, either. ORACLE Enterprise Server has the problem as well. In fact, it became bad enough that ORACLE (over 15 years ago) added "backup mode" operation to quiesce all table update operations so that you could take a snapshot of your DB when nothing was going on. The transactions were stored in a separate table and then rolled forward AFTER the backup was finished. Failure to enter backup mode before doing a backup led to "instantiation number inconsistent" errors.

The problem is simple: A snapshot is only crisp and clear when no-one and nothing are moving. A photo taken with typical 3-6 year old kids will have blurs unless the kids have been given a couple of shots of whiskey or a Xanax to get them lethargic. A database backup is just a digital snapshot of the database file. The database file, if very large, cannot be copied instantly. And if anyone is operating in the DB at that time, they are moving things around while you are trying to take your snapshot. Can you say "blurry image"? I knew you could.

The idea of picking a time when no one is on the DB and then having an external script do a Windows-level file copy & rename is VERY likely to work correctly. Opening the DB to make a backup copy from within Access only works reasonably if you open the DB in Exclusive mode.
 
If the database is open at the time of that backup operation, there is a VERY STRONG possibility that a backup taken at that moment will be unusable.
• I routinely make a backup copy of our BE table at work. It is almost never in a state where zero FEs are connected to it. I have never had the experience that the copy I made is unusable.
• For a while, when I was getting a lot of FE crashes during development, I wrote code that made a backup copy of the FE from the FE itself. I never experienced that my FE copy was unusable. Indeed I much more commonly experienced corruption in the live FE in-development file, and my FE copy, taken from the FE itself while it was open, saved my bacon.
• Though it is conventional wisdom that taking a copy of an open database file is a risk, in practice I have never experienced a failure.
 
point 1 on markk's post #6 is correct.
the backup must took place when the BE is not in used.
that is what my code actually do.
it check first if the BE is free and back it up.
otherwise no backup is created.
 
I should also say, most backups I make never get touched. So I can't claim it always works, only that it always has when I've needed it to.

The thing is, with the Navy we had to verify every so often because they were freakin' PARANOID about backups and recoverability. So I had to test backups once per month. And every so often, we had a little "whoops" that required me to perform a manual out-of-cycle backup.

In case anyone is wondering about why backing up the BE is so touchy, just remember that the work done TO the BE is managed in the memory of the FE, and until any pending update has been fully written to the BE, it is entirely possible that a snapshot would capture the incomplete update and make the DB in an inconsistent state. One good, large UPDATE that spanned a few thousand records would be all you need to bollix up the works.
 
• I routinely make a backup copy of our BE table at work. It is almost never in a state where zero FEs are connected to it. I have never had the experience that the copy I made is unusable.
• For a while, when I was getting a lot of FE crashes during development, I wrote code that made a backup copy of the FE from the FE itself. I never experienced that my FE copy was unusable. Indeed I much more commonly experienced corruption in the live FE in-development file, and my FE copy, taken from the FE itself while it was open, saved my bacon.
• Though it is conventional wisdom that taking a copy of an open database file is a risk, in practice I have never experienced a failure.
That has been my experience as well.
For the few clients that are on Access BE, we run a PowerShell script every 15 min during business hours to make a backup, and to trim back the files to the last 2 weeks. Even if there is a bad one, I have another one from 15 min earlier.
Sorry I cannot share the script, but I'm sure you can have an AI create it for you.
 
It has been my experience back in the days when I sold commercial software that if a backup is started when the BE is in use somewhere, editing or not, it will be incomplete. I would advise customers to do at least Odd and Even backups onto separate odd and even disks, or USBs. That way they never just had one backup from the previous day, which could be bad. Some companies would do daily backups and never overwrite. I did have one client who did make regular backups but was burgled. The thieves took their computers and the contents of the desk drawer when he threw his backups!
I do suspect that most PC users don't backup their important stuff even now. And those using mobile phones as their computer, will not have any backups at all.

Any tables in use will simply be omitted. As confirmed in #2, #5 & #9. I will say that maybe 99% of backups are never needed. However, when you hit the 1%, just as a feeling of great foreboding and panic sets in, you just cannot find enough of them.

As I 've said before on the forum: You cannot be too thin, too rich, or have too many backups.
 
Last edited:
• I routinely make a backup copy of our BE table at work. It is almost never in a state where zero FEs are connected to it.
Never had to do it since but 'just in case' we had code which stopped people logging in at BU time (0200). Can't actually say if it was ever invoked as we had no feedback one way or the other.
 
for automatic backup whenever the front-end is closed, you will need a startup, hidden form that when closed will
do the backup.
copy this to a module:
Code:
Function IsBackendInUse() As Boolean
    Dim strBackendPath As String
    Dim intFileNum As Integer
   
    strBackendPath = BackEndPath()
   
    On Error Resume Next
    intFileNum = FreeFile
    Open strBackendPath For Binary Access Read Lock Read Write As #intFileNum
    Close #intFileNum
   
    If Err.Number <> 0 Then
        IsBackendInUse = True  ' File is locked
    Else
        IsBackendInUse = False ' File is available
    End If
    On Error GoTo 0
End Function

Public Sub BackupBackendDatabase()
    Dim strSourcePath As String
    Dim strBackupPath As String
    Dim strBackupFileName As String
   
    ' change this to the correct path to your backup folder
    strBackupPath = Environ("userprofile") & "\documents\backup\"
   
    ' Path to your backend database
    strSourcePath = BackEndPath()
   
    ' Backup location with timestamp
    'strBackupFileName = GetBaseName(strSourcePath) & "_" & Format(Now(), "yyyy-mm-dd_hhnnss") & "." & GetExtension(strSourcePath)
    Dim strBaseName As String
    strBaseName = GetBaseName(strSourcePath)
    If Right(strBaseName, 3) = "_be" Then
        strBackupFileName = Left$(strBaseName, Len(strBaseName) - 3) & Format$(Date, "mmm") & "_be"
    Else
        strBackupFileName = GetBaseName(strSourcePath) & Format$(Date, "ddd")
    End If
    strBackupFileName = strBackupFileName & "." & GetExtension(strSourcePath)
   
   
    ' Create backup folder if it doesn't exist
    If Dir(strBackupPath, vbDirectory) = "" Then
        MkDir strBackupPath
    End If
    strBackupPath = strBackupPath & strBackupFileName
   
    ' Copy the backend database
    On Error Resume Next
    FileCopy strSourcePath, strBackupPath
   
    If Err.Number = 0 Then
        MsgBox "Backup created successfully: " & strBackupFileName, vbInformation
    Else
        MsgBox "Backup failed: " & Err.Description, vbExclamation
    End If
    On Error GoTo 0
End Sub


Public Function BackEndPath$()
Const conString = ";DATABASE="
Dim td As DAO.TableDef
Dim db As DAO.Database: Set db = CurrentDb
Dim conn$
For Each td In db.TableDefs
    conn = td.Connect
    If Len(conn) <> 0 Then
        If InStr(1, conn, conString) = 1 Then
            BackEndPath = Mid$(conn, Len(conString) + 1)
            Exit For
        End If
    End If
Next
Set td = Nothing: Set db = Nothing
End Function


' helper
Function GetFileName(strPath As String) As String
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetFileName = fso.GetFileName(strPath)
    Set fso = Nothing
End Function

Function GetExtension(strPath As String) As String
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetExtension = fso.GetExtensionName(strPath)
    Set fso = Nothing
End Function

Function GetBaseName(strPath As String) As String
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetBaseName = fso.GetBaseName(strPath)  ' Filename without extension
    Set fso = Nothing
End Function

now add code to the Close Event of your hidden, start-up form:
Code:
Private Sub Form_Close()
    If IsBackendInUse() Then
        MsgBox "Backup skipped - other users are currently accessing the database.", vbInformation
        Exit Sub
    End If

    Call BackupBackendDatabase
End Sub
Thanks Arnelgp,
When you say when front end is closed, I have 3 users via runtime, so would the code run every time they close
 
it would
When you say when front end is closed, I have 3 users via runtime, so would the code run every time they close
yes it would, but only when no table/query, form (bound), report is open.
if the BE is used by another user, it won't get backup.
it will only get backup by the last user of your app upon closing.
 
Clean backups are always an issue. I have users, some of them upper management that constantly leave computers logged in overnight with multiple programs open with multiple network files open, including Access FEs. The shadow copies and backups tend to work. I always do a compact/repair after restoring one. Once a month I do a manual copy of the BE and a compact/repair on the production FE, after kicking those uses off the server and clearing the locks.

Same issues with security. The higher up the user. The more likely they will be click happy; opening every link sent to them. The only time some can follow instructions are those in some random email explaining how to download and install some file, bypassing warnings about the safety of that file.
 
Just wondering if anyone has created a routine that carries out a daily backup of the backend database to cover each weekday
So on this Tuesday it backs up database_be.accdb to databaseTue_be.accdb, then overwrites next week etc
Always be sure to double check with your IT department to ensure they don't already have the file server backed up.
If they do, you might be able to right click the folder, go to Properties, then Previous Versions, and see days or weeks worth of backed up files / folders there at any given time. The backing up of data usually belongs to the IT dept and should be left up to them, IMHO. I mean, if such is the case.
I say this only because various times I've made the mistake of dumping a lot of time into backing things up and then realized the company already had such a robust process in place that mine was totally unnecessary
 
Yeah, I never bothered with any data backups since IT already had it in their rotation.
I posted earlier about using shadow copy and server backups. The consensus appears to be that it can be un-reliable if the BE is open during the backup. I have used shadow copies to recover older versions of the BE to restore data changed by users. I have not had issues but others say I was lucky.
 
A warning - learned the hard way - make sure that Back-Ups being taken by the 'system' include everything you think they do IT departments are selective about what they think is, and isn't, important. Also get a back-up and see if it actually works.
 

Users who are viewing this thread

Back
Top Bottom