Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recover a corrupt SQLite3 database?

This is a follow up question to a previously answered post: Is there a command line utility for validating SQLite databases in Linux?

If a database is producing the following error:

$ sqlite3 mydata.db "PRAGMA integrity_check" Error: database disk image is malformed 

Is there any cleanup processing that can be done to recover the database to a usable state? Even at the potential loss of some corrupt records?

Thanks

like image 599
linsek Avatar asked Aug 15 '13 18:08

linsek


People also ask

Can SQLite be corrupted?

Since SQLite databases are ordinary disk files, any malfunction in the filesystem can corrupt the database. Filesystems in modern operating systems are very reliable, but errors do still occur.

How can I tell if SQLite database is corrupted?

To verify that you're truly suffering from database corruption, enter the following command into the shell: sqlite> PRAGMA integrity_check; If the response is anything other than ok, the database is integrity checks have failed and needs to be repaired.


1 Answers

UPDATE: There is now an automatic method that is built into SQLite: .recover

Sometimes, the corruption is only or mostly in indexes, in which case it would be possible to get some or most records by trying to dump the entire database with .dump, and use those commands to create a new database:

$ sqlite3 mydata.db ".dump" | sqlite3 new.db 

However, this is not always possible.

The easiest and most reliable way is to restore the database file from the backup.

like image 152
CL. Avatar answered Sep 17 '22 23:09

CL.