Recently encountered a problem, user data loss, to get the user database files, the discovery of database corruption.
database disk image is malformed
So hope to find a way to detect whether the database is damaged, after Google, found a method, first recorded.
+ (BOOL) checkintegrity {nsstring *databasepath = [self databasefilepath]; File NOT EXISTS = okay if (! [[Nsfilemanager Defaultmanager] Fileexistsatpath:databasepath]) {return YES; } const CHAR *filename = (const char *) [DatabasePath cstringusingencoding:nsutf8stringencoding]; Sqlite3 *database = NULL; if (Sqlite3_open (filename, &database)! = SQLITE_OK) {sqlite3_close (database); return NO; } BOOL integrityverified = NO; sqlite3_stmt *integrity = NULL; if (SQLITE3_PREPARE_V2 (Database, "PRAGMA integrity_check;",-1, &integrity, NULL) = = Sqlite_ok) {while (s Qlite3_step (Integrity) = = Sqlite_row) {Const unsigned char *result = sqlite3_column_text (integrity, 0); If (Result && strcmp (const char *) result, (const char *) "OK") = = 0) {integrityverified = YES; Break }} sqlite3_finalize (integrity); } sqlite3_close (database); return integrityverified;}
Original link
PRAGMA Schema.integrity_check;
PRAGMA Schema.integrity_check (N)
This pragma does a integrity check of the entire database. The integrity_check pragma looks for Out-of-order records, missing pages, malformed records, missing index entries, and UN IQUE and not NULL constraint errors. If the Integrity_check pragma finds problems, strings is returned (as multiple rows with a single column per row) which D Escribe the problems. Pragma Integrity_check would return at the very n errors before the analysis quits, with N defaulting to 100. If pragma integrity_check finds no errors, a single row with the value ' OK ' is returned.
Focus on this sentence as multiple rows with a single column per row)
In this way, it can be implemented by C code.
Depending on the document, you can also use Quick_check to check.
PRAGMA Schema.quick_check;
PRAGMA Schema.quick_check (N)
The pragma is a like integrity_check except, it does not verify UNIQUE and not NULL constraints and does not verify that Index content matches table content. By skipping UNIQUE and not NULL and index consistency checks, Quick_check are able to run much faster than Integrity_check. Otherwise the pragmas is the same.
The difference is that Integrity_check checked.
-Out-of-order Records (record of disorderly order)
-Missing Pages (pages)
-Malformed records (wrong record)
-Missing index entries (missing index)
-Unique constraint (uniqueness constraint)
-NOT NULL (non-null constraint)
And it takes more time.
Quick_check does not check constraints and takes less time
Check SQLite Database Integrity