最近有這麼一個需求,數據庫初始的時候就已經有一個表中有數據了,這致使咱們以前在程序運行的時候,再在本地建立數據庫的方案不能使用了.由於程序運行時,再建立數據庫和表,確定都是空的.若是要有數據,就必須寫n多條的插入語句.最終,咱們以爲把已經建立好的數據庫,放到工程文件,Supporting Files 中.而後在程序運行的時候,把數據庫移動到本地,做爲本地數據庫使用.數據庫
// SQLManager.h數組
#import <Foundation/Foundation.h>atom
@interface SQLManager : NSObjectspa
+ (instancetype)sharedMapSQLite;.net
- (NSArray *)totalGroupOfT_cityWithNameSort:(NSString *)nameSort;3d
@end orm
// SQLManager.mci
#import "SQLManager.h"get
#import "FMDB.h"string
@interface SQLManager ()
@property (nonatomic, strong) FMDatabaseQueue* queue;
@implementation SQLManager
+ (instancetype)sharedSQLManager {
static SQLManager* manager;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[MapSQLite alloc] init];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
path = [path stringByAppendingPathComponent:@"list.db"];
NSData *data=[NSData dataWithContentsOfFile:path];
if (!data) {
NSString *backupDbPath = [[NSBundle mainBundle]
pathForResource:@"list"
ofType:@"db"];
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error;
BOOL cp = [fm copyItemAtPath:backupDbPath toPath:path error:&error];
NSLog(@"%@",error);
}
manager.queue = [FMDatabaseQueue databaseQueueWithPath:path];
NSLog(@"path == %@",path);
});
return manager;
}
//根據傳入的字母主鍵 返回主鍵所在色數組
- (NSArray *)totalGroupOfT_cityWithNameSort:(NSString *)nameSort
{
NSString* loadStatement = @"SELECT * FROM T_city WHERE nameSort = ?;";
NSMutableArray *arrayM = [NSMutableArray array];
[self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
FMResultSet* result = [db executeQuery:loadStatement withArgumentsInArray:@[nameSort]];
while ([result next]) {
NSString *strgroup = [result stringForColumn:@"CityName"];
[arrayM addObject:strgroup];
}
}];
return arrayM.copy;
}
// 調用
SQLManager *manager = [SQLManager sharedMapSQLite];
NSArray *array = [manager totalGroupOfT_cityWithNameSort:@"A"];
NSLog(@"%@",array);