(iOS)读取db数据库

一般除了网络请求数据外,我们的项目中还会遇到导入本地数据库(db)。今天主要分享如何获取db数据库中的所有字段和数据。

首先我们需要导入依赖框架FMDB,将我们所需读取的db数据库拖入项目中

本地数据库

展示sql下的数据库里的数据

(iOS)读取db数据库_第1张图片
Navicat
CREATE TABLE "nba_star" (
  "nID" integer,
  "name" text,
  "age" integer,
  "team" text,
  "highest" integer
);

-- ----------------------------
-- Records of "nba_star"
-- ----------------------------
BEGIN;
INSERT INTO "nba_star" VALUES (1, '哈登', 28, '休斯顿火箭', 56);
INSERT INTO "nba_star" VALUES (2, '库里', 29, '金州勇士', 54);
INSERT INTO "nba_star" VALUES (3, '詹姆斯', 32, '克利夫兰骑士', 61);
INSERT INTO "nba_star" VALUES (4, '维斯布鲁克', 28, '俄克拉荷马城雷霆', 54);
INSERT INTO "nba_star" VALUES (5, '保罗', 32, '休斯顿火箭', 43);
INSERT INTO "nba_star" VALUES (6, '杜兰特', 29, '金州勇士', 54);
COMMIT;
PRAGMA foreign_keys = true;

创建模型文件nbaStarItem 和一个可读去数据的文件DCReadDBSQL

nbaStarItem.h
/* id */
@property (nonatomic, copy) NSString *nID;
/* 名字 */
@property (nonatomic, copy) NSString *name;
/* 年龄 */
@property (nonatomic, copy) NSString *age;
/* 球队 */
@property (nonatomic, copy) NSString *team;
/* 生涯最高分 */
@property (nonatomic, copy) NSString *highest;

DCReadDBSQL.h
/**
  读取db数据库中所有字段
 @return 字典
 */
+ (NSMutableDictionary *)dc_readDBColumnNameToIndexMap;

/**
 读取db数据库中所有数据
 @return 数组
 */
+ (NSMutableArray *)dc_getDBArrayWithdbArray;
DCReadDBSQL.m
#pragma mark - 读取字段
+ (NSMutableDictionary *)dc_readDBColumnNameToIndexMap
{
    NSString *table = [NSString stringWithFormat:@"select * from %@",TABLENAME];
    NSString *dbPath = [[NSBundle mainBundle]pathForResource:DBNAME ofType:@"db"];
    FMDatabase *database = [ FMDatabase databaseWithPath:dbPath];
    if (![database open]) return 0;
    // 查找表 AllTheQustions
    FMResultSet *resultSet = [database executeQuery:table];
    resultSet = [database executeQuery:table];
    
    //读取table表中所有字段
    return resultSet.columnNameToIndexMap;
}
#pragma mark - 读取数据
+ (NSMutableArray *)dc_getDBArrayWithdbArray
{
    NSString *table = [NSString stringWithFormat:@"select * from %@",TABLENAME];
    NSString *dbPath = [[NSBundle mainBundle]pathForResource:DBNAME ofType:@"db"];
    FMDatabase *database = [ FMDatabase databaseWithPath:dbPath];
    if (![database open]) return 0;
    // 查找表 AllTheQustions
    FMResultSet *resultSet = [database executeQuery:table];
    resultSet = [database executeQuery:table];
    
    NSMutableArray *array = [NSMutableArray array];
    // 循环逐行读取数据resultSet next
    while ([resultSet next])
    {
        nbaStarItem *item = [[nbaStarItem alloc] init]; //给模型赋值
        item.nID = [resultSet stringForColumn:@"nID"];
        item.name = [resultSet stringForColumn:@"name"];
        item.age = [resultSet stringForColumn:@"age"];
        item.team = [resultSet stringForColumn:@"team"];
        item.highest = [resultSet stringForColumn:@"highest"];
        
        [array addObject:item];
    }
    
    [database close]; //关闭
    
    return array;
}
RUN.........
(iOS)读取db数据库_第2张图片
断点图

你可能感兴趣的:((iOS)读取db数据库)