以下代碼適用于直接在代碼中操作數(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];
}