如何读取db文件中的数据

项目中需要获取所有城市
先找到一个db文件,可以去网上搜一个db文件,下载地址http://download.csdn.net/detail/u010827511/5446157
使用了FMDB第三方
需要添加库文件 targets——>Build Phases——>Link Binary With Libraries
+libsqlites.tbd

#pragma mark ---- 获取城市信息
- (void)loadAddress {
    NSString *str = [[NSBundle mainBundle] resourcePath];
    NSString *databasePath = [str stringByAppendingPathComponent:@"address.db"];
    
    NSMutableArray *address = [[NSMutableArray alloc] initWithCapacity:35];
    FMDatabase *fmdb = [FMDatabase databaseWithPath:databasePath];
    [fmdb open];
    
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM tbl_helper_locations WHERE parent_id = 0"];
    FMResultSet *rs = [fmdb executeQuery:sql];
    while ([rs next]) {
        NSString *addressName = [rs stringForColumn:@"name"];
        NSMutableArray *atomicArr = [[NSMutableArray alloc] init];
        NSString *atomicId = [rs stringForColumn:@"id"];
        NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM tbl_helper_locations WHERE parent_id = %@", atomicId];
        FMResultSet *resultSet = [fmdb executeQuery:sqlStr];
        while ([resultSet next]) {
            NSString *atomicStr = [resultSet stringForColumn:@"name"];
            [atomicArr addObject:atomicStr];
        }
        if (atomicArr.count) {
            [address addObject:@{addressName: atomicArr}];
        }
    }
    // 得到所有省市的数组
    _address = address.mutableCopy;
}

你可能感兴趣的:(如何读取db文件中的数据)