sqlite,FMDB簡單使用

以下代碼適用于直接在代碼中操作數(shù)據(jù)庫,實際中可以使用navicat圖形化界面先進行數(shù)據(jù)庫測試數(shù)據(jù)的填充,在APP啟動時,將.sqlite文件拷貝至沙盒目錄下

1.創(chuàng)建數(shù)據(jù)庫
#define DBNAME @"testDB.sqlite"
-(void)creatDataBase
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];

BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:database_path];
if (isExist) {
    return;
}

FMDatabase *db = [FMDatabase databaseWithPath:database_path];
if (![db open]) {
    NSLog(@"打開數(shù)據(jù)庫失敗");
  }
}

2.創(chuàng)建表t_test
ID主鍵,自增整型,向表中添加數(shù)據(jù)時ID填NULL即可;BLOB存儲二進制數(shù)據(jù)

NSString *sqlCreateTable = @"CREATE TABLE IF NOT EXISTS t_test (ID INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT,thumb BLOB)";
[db executeUpdate:sqlCreateTable];

3.向表中添加數(shù)據(jù)

//將數(shù)組類型轉(zhuǎn)成NSData對應數(shù)據(jù)庫BLOB類型
 NSArray *imgAry = @[@"aa",@"bb",@"cc"];
 NSData *imgData = [NSKeyedArchiver archivedDataWithRootObject:imgAry];

[db executeUpdate:@"INSERT INTO t_test (ID, title,thumb) VALUES (?,?,?)",
 [NSNumber numberWithInt:1],@"xxxxx",
 ];

4.獲取數(shù)據(jù)庫中的數(shù)據(jù)
假設Test類有三個屬性對應表中三個字段,dataArray就是獲取到的數(shù)據(jù)庫中的數(shù)據(jù)

FMDatabase *db = [FMDatabase databaseWithPath:database_path];
if (![db open]) {
    NSLog(@"打開數(shù)據(jù)庫失敗");
}else{
    FMResultSet *rs = [db executeQuery:@"SELECT * FROM t_test"];
    NSMutableArray *dataArray = [NSMutableArray array];
    while ([rs next]) {
        Test *test = [[Test alloc] init];
        test.id = [rs intForColumn:@"ID"];
        test.title = [rs intForColumn:@"title"];
        test.thumb = [NSKeyedUnarchiver unarchiveObjectWithData:[rs dataForColumn:@"thumb"]];
    [dataArray addObject:test];
    } 
    [rs close];
}
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容