VistaDB 6
VistaDB / Developer's Guide / How To Perform Common Tasks / How To - Backup and Restore a Database
In This Topic
    How To - Backup and Restore a Database
    In This Topic

    VistaDB database are entirely self contained within a single file, making archive options easy with most scenarios covered simply by making a copy of the file.

    VistaDB also includes a dedicated pair of functions to backup a database that will create a compressed copy, even if it's an encrypted database.

    Backing up a Database

    To make a backup of a database, first open the database and then call BackupDatabase on the VistaDBConnection instance. 

    // Create your connection string (note the open mode restrictions)
    var csb = new VistaDBConnectionStringBuilder();
    csb.DataSource = "your_database.vbd6";
    csb.OpenMode = VistaDBDatabaseOpenMode.ExclusiveReadOnly;
    
    // Create a connection to the database and then archive it.
    using (var conn = new VistaDBConnection(csb.ToString()))
    {
        var backupFileName = "database.vdbzip";
        File.Delete(backupFileName);
        conn.BackupDatabase(backupFileName);
    }
    

    To backup a database, you have to open it in a mode that prevents modification from any other connection - so the open mode needs to either be an exclusive mode or Shared Read Only.

    The archive file must not already exist when calling CompressDatabase.  If it does, an IOException will be thrown.

    Restoring a Backup

    You can restore a database backup made by BackupDatabase by using RestoreDatabase.  This will create a new database file with the read-to-access contents of the archived database.  RestoreDatabase is a static method and doesn't need a connection to the database to work.  If the original database was encrypted, the encryption passwod must be provided.

    // Restore a backup file into a new database file (for an unencrypted database)
    VistaDBConnection.RestoreDatabase(archiveFileName, targetFileName);
    
    // Restore a backup file into a new database file (for an encrypted database)
    VistaDBConnection.RestoreDatabase(archiveFileName, targetFileName,
        "your_database_password");
    

    Working with Streams

    Backup can be done to and from a data stream as well for advanced scenarios. Use the overloads of BackupDatabase and RestoreDatabase that accept streams.

    How is Backup Different than Packing?

    Backing up a database performs a low-level archive by compressing each individual page of data in the original database. It doesn't drop unused pages or data, and it doesn't do database integrity checks.  It's generally much faster than Pack, but the restored database will have the same size and structure as the original database prior to it being archived.

    Packing a database is an important maintenace procedure which rebuilds indexes, drops unused rows and reclaims empty space.

    See Also