检测sqlite3数据库的完整性
1 /** 2 * @integrityCheck 3 * @brief 检查数据库的完整性 4 * 5 * @param dbPath 数据库的路径 6 * @返回值 0:完整; -1 损坏 7 */ 8 int integrityCheck(const char *dbPath) 9 { 10 int ret = -1; 11 sqlite3_stmt *integrity = NULL; 12 sqlite3 *db; 13 /*打开数据库*/ 14 if (sqlite3_open(dbPath, &db) != SQLITE_OK) 15 { 16 logPrintf(LOG_LIB_ERROR, "Open database %s failed!\n", dbPath); 17 return ret; 18 } 19 20 // integrity_check检查包括:乱序的记录、缺页、错误的记录、丢失的索引、唯一性约束、非空约束 21 //if ( sqlite3_prepare_v2( obj_db, "PRAGMA integrity_check;", -1, &integrity, NULL ) == SQLITE_OK ) 22 //quick_check不检查约束条件,耗时较短 23 if ( sqlite3_prepare_v2(db, "PRAGMA quick_check;", -1, &integrity, NULL) == SQLITE_OK ) 24 { 25 while (sqlite3_step(integrity) == SQLITE_ROW) 26 { 27 const unsigned char *result = sqlite3_column_text(integrity, 0); 28 if (result && strcmp((const char *)result, (const char *)"ok") == 0) 29 { 30 ret = 0; 31 break; 32 } 33 } 34 35 sqlite3_finalize(integrity); 36 } 37 38 /*关闭数据库*/ 39 sqlite3_close(db); 40 41 return ret; 42 }