码迷,mamicode.com
首页 > 数据库 > 详细

检查sqlite数据库完整性

时间:2016-10-13 01:35:39      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:

最近遇到一个问题,用户数据丢失,拿到用户数据库文件以后,发现数据库损坏。

database disk image is malformed

因此希望可以找到一种方法,可以检测出来数据库是否损坏,经过google,找到了一种方法,先记录下来。

+ (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 ( sqlite3_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;
}

原链接

PRAGMA schema.integrity_check;
PRAGMA schema.integrity_check(N)

This pragma does an integrity check of the entire database. The integrity_check pragma looks for out-of-order records, missing pages, malformed records, missing index entries, and UNIQUE and NOT NULL constraint errors. If the integrity_check pragma finds problems, strings are returned (as multiple rows with a single column per row) which describe the problems. Pragma integrity_check will return at most 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.

重点在这句话as multiple rows with a single column per row)
这样子,可以通过c代码来实现
根据文档,也可以使用quick_check来检查。

PRAGMA schema.quick_check;
PRAGMA schema.quick_check(N)

The pragma is like integrity_check except that 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 is able to run much faster than integrity_check. Otherwise the two pragmas are the same.

区别在于integrity_check检查了
- out-of-order records(乱序的记录)
- missing pages(缺页)
- malformed records(错误的记录)
- missing index entries(丢失的索引)
- UNIQUE constraint(唯一性约束)
- NOT NULL (非空约束)
而且耗时较多。
quick_check不检查约束条件,耗时较短

检查sqlite数据库完整性

标签:

原文地址:http://www.cnblogs.com/huahuahu/p/jian-chasqlite-shu-ju-ku-wan-zheng-xing.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!