FMDatabase 數據庫
1.下載FMDatabase 導入下載裡面的src文件,刪了fmdb.m文件 2.引入framework:libsqlite3.dylib 3.引入頭文件 #import "FMDatabase.h” 數據庫文件要兼容iPhone4和iPhone5需要放在Document或Library目錄中,先判斷Document/Library中數據庫文件(一般是.sqlite後綴)是否存在,如果不存在則從工程(bundle)中把數據庫文件拷貝到Document中或Library中。
以下是我是我工程中用過的一個數據庫操作代碼,記下來,免得忘記了: [cpp] view plaincopyprint?
- //數據庫操作,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...");
-
-
- }