FMDatabase 数据库
1.下载FMDatabase
导入下载里面的src文件,删了fmdb.m文件
2.引入framework:libsqlite3.dylib
3.引入头文件
#import "FMDatabase.h”
数据库文件要兼容iPhone4和iPhone5需要放在Document或Library目录中,先判断Document/Library中数据库文件(一般是.sqlite后缀)是否存在,如果不存在则从工程(bundle)中把数据库文件拷贝到Document中或Library中。
以下是我是我工程中用过的一个数据库操作代码,记下来,免得忘记了:
//数据库操作,1代表增减,2代表删除,3,代表查询,4,代表修改 -(void)operateDB:(NSInteger)num andRow:(NSInteger)row status:(NSInteger)status{ self.deleteOld = YES; self.dbFile = @"shopCar_db.sqlite"; NSFileManager *manager = [NSFileManager defaultManager]; NSString *dbPath = [Utilities documentsPath:self.dbFile]; //没存在则拷贝到document if (![manager fileExistsAtPath:dbPath]) { NSString *bundlePath = [Utilities bundlePath:self.dbFile]; if ([manager copyItemAtPath:bundlePath toPath:dbPath error:nil]) { NSLog(@"copy ok..."); } else { NSLog(@"copy error..."); } } else{ if (self.deleteOld) { NSLog(@"delete old and create new.."); NSString *bundlePath = [Utilities bundlePath:self.dbFile]; [manager removeItemAtPath:dbPath error:nil]; [manager copyItemAtPath:bundlePath toPath:dbPath error:nil]; } else { NSLog(@"do nothing..."); } } FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; NSLog(@"begin to db..."); if ([db open]) { if(status == 1){ NSLog(@"增减......."); } if(status == 2){ NSString *sql = [NSString stringWithFormat:@"delete from shopCar_tb where id = %i",row]; [db executeUpdate:sql]; } if(status == 3){ NSLog(@"查询........"); } if(status == 4){ NSString *sql = [NSString stringWithFormat:@"UPDATE shopCar_tb SET num = '%d' WHERE id = %d",num,row]; [db executeUpdate:sql]; } NSString *sql = @"select * from shopCar_tb"; FMResultSet *result = [db executeQuery:sql]; _mutableArrayData = [[NSMutableArray alloc] init]; [_mutableArrayData removeAllObjects]; [_mutableDictionayData removeAllObjects]; while ([result next]) { _mutableDictionayData = [[NSMutableDictionary alloc] init]; NSString *sid = [result stringForColumn:@"id"]; [_mutableDictionayData setObject:sid forKey:@"id"]; NSString *name = [result stringForColumn:@"name"]; [_mutableDictionayData setObject:name forKey:@"name"]; NSString *gid = [result stringForColumn:@"gid"]; [_mutableDictionayData setObject:gid forKey:@"gid"]; NSString *num = [result stringForColumn:@"num"]; [_mutableDictionayData setObject:num forKey:@"num"]; NSLog(@"num = %i",[num intValue]); NSString *price = [result stringForColumn:@"price"]; [_mutableDictionayData setObject:price forKey:@"price"]; NSString *path = [result stringForColumn:@"path"]; [_mutableDictionayData setObject:path forKey:@"path"]; [_mutableArrayData addObject:_mutableDictionayData]; } } [db close]; NSLog(@"end db..."); }