You are here: Troubleshooting > Investigate a Corrupt Database

Deal With a Corrupt Database

In general you should do regular backups of your database. db4o tries to do its best to never corrupt the database. However due to bugs or external reasons corruption can occur. Check also your configuration to not use any risky settings.

If you have a corrupted database you may think about reporting it: See "Report Bugs"

The fist step is to run the consistency check on your database. If the database is really corrupt you can try to restore at least some your data.

Consistency Check

To run consistency checks use the com.db4o.consistency.ConsistencyChecker class, like this:

java -cp db4oX-X.XX-all-java5.jar com.db4o.consistency.ConsistencyChecker databaseFile.db4o

This consistency check doesn't check the content of objects. It only checks if the overall structure of the database file is still intact. Also it doesn't offer any repair functionality. It only tells you if the file is corrupted or not.

When the tool reports inconsistencies you've defiantly have a corrupted database. Then you should fall back to the latest backup or try to recover parts of the database.

In case the tool doesn't report any issues you maybe still have a corrupted object in your database. In that case you usually can read all intact objects and copy them to a new database.

Try to Restore Intact Objects

When you cannot read some particular object then you can try to read and copy the intact objects over to a new database. You can get the id of all objects for a certain type. With these ids you then can load each single object. When loading an object fails then that object is lost. However you still can store the intact objects to another storage.

final long[] idsOfPersons = container.ext().storedClass(Person.class).getIDs();
for (long id : idsOfPersons) {
    try{
        final Person person = (Person)container.ext().getByID(id);
        container.ext().activate(person,1);
        // store the person to another database
        System.out.println("This object is ok "+person);
    } catch (Exception e){
        System.out.println("We couldn't read the object with the id "+id +" anymore." +
                " It is lost");
        e.printStackTrace();
    }
}
TryToReadSingleObjects.java: Try to read the intact objects