標籤:style blog color os io 使用 ar for 檔案
1.把資料庫檔案localdata.db放入工程,並建立bundle(在build phases裡)
2.建立新的類,用於本地SQLite查詢. LocalDB.m(.h就不說了,保證每個.m裡要外部調用的函數都在.h裡做好介面就好)
3.LocalDB.m: createDB函數
因為工程裡的Bundle檔案無法直接使用(只能直接使用document裡的檔案),所以第一次使用sqlite檔案要把它複製到document檔案夾。
-(void)createDB{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //該方法可用來顯示DOCUMENT檔案夾內的檔案資訊 NSString *documents = [paths objectAtIndex:0]; database_path = [documents stringByAppendingPathComponent:DBNAME];//擷取資料庫檔案的地址,不存在就會建立 NSLog(@"資料庫地址是:%@",database_path); //根據上面拼接好的路徑 dbFilePath ,利用NSFileManager 類的對象的fileExistsAtPath方法來檢測是否存在,返回一個BOOL值 //1. 建立NSFileManager對象 NSFileManager包含了檔案屬性的方法 NSFileManager *fm = [NSFileManager defaultManager]; //2. 通過 NSFileManager 對象 fm 來判斷檔案是否存在,存在 返回YES 不存在返回NO BOOL isExist = [fm fileExistsAtPath:database_path]; //NSLog(@"isExist =%d",isExist); //如果不存在 isExist = NO,拷貝工程裡的資料庫到Documents下 if (!isExist) { //拷貝資料庫 //擷取工程裡,資料庫的路徑,因為我們已在工程中添加了資料庫檔案,所以我們要從工程裡擷取路徑 NSString *backupDbPath = [[NSBundle mainBundle] pathForResource:@"localdata" ofType:@"db"]; BOOL cp = [fm copyItemAtPath:backupDbPath toPath:database_path error:nil]; NSLog(@"找到Bundle檔案:%@,已拷貝至Document",backupDbPath); } if (sqlite3_open([database_path UTF8String], &db) != SQLITE_OK) { sqlite3_close(db); NSLog(@"資料庫開啟失敗"); } sqlite3_close(db);}
4.簡單的查詢語句(我建立了一個dbversion的table,然後欄位為dbversion,值為1.0,用於以後的更新)
這是一個最簡單的sqlite的查詢語句用法。
-(NSString *)selectdbversion{ NSString * version; if (sqlite3_open([self->database_path UTF8String], &db) == SQLITE_OK){ NSString *sqlQuery =@"SELECT dbversion FROM dbversion"; sqlite3_stmt * statement; if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) { while (sqlite3_step(statement) == SQLITE_ROW) { char *row0 = (char*)sqlite3_column_text(statement, 0); version = [[NSString alloc]initWithUTF8String:row0]; } }else { NSLog( @"Failed from sqlite3_prepare_v2. Error is: %s", sqlite3_errmsg(db) ); } } return version;}
5.外部調用方式:
執行個體化localDB對象就可以了。
LocalDB *newdb=[LocalDB alloc]; [newdb createDB]; NSString *version=[newdb selectdbversion]; NSLog(@"%@",version);
[IOS SQLITE的使用方式]