星空网 > 软件开发 > 操作系统

检查sqlite数据库完整性

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

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数据库完整性

关键词:sql

sql
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流