因为App本地数据库要升级,就涉及到数据迁移问题,网上的大多数例子都是同一个db文件中的数据表的数据迁移,对于夸数据库的迁移,资料少之。 百度之,发现sqlite3支持附加数据库。看了语法却不知道怎么用之。没有找到一个例子。最后自行尝试,居然成功了。
关于app本地数据库升级的文章,可参考:https://www.jianshu.com/p/b763434fd33a
此外,截止文章发布,FMDB中没有任何数据库附加的内容哈。
iOS Sqlite附加数据库,并实现数据迁移
现有数据库old_diary.db 和 diary.db, 它们有两张相同的表 task_table 。现在要把old_diary.db 中的task_table表数据全部迁移至diary.db的task_table表中。代码如下:
- (void)moveOldTaskData{
///数据库路径
NSString *oldDbPath = [self getDbPathWithName:@"old_diary.db"];
NSString *dbPath = [self getDbPathWithName:@"diary.db"];
if( oldDbPath == nil || dbPath == nil ) return;
///附加数据库语法
///"ATTACH DATABASE '待附加的数据库路径' AS 名字"
///附加数据库语句: 我们将old_diary.db附加到diary.db上
const char* attachSql = [[NSString stringWithFormat:@"ATTACH DATABASE '%@' AS OldDiaryDB",oldDbPath] UTF8String];
sqlite3 *diaryDB;
if (sqlite3_open([dbPath UTF8String], &diaryDB) == SQLITE_OK) {
//将old_diary.db附加到diary.db上,并起名字为OldDiaryDB
sqlite3_exec(diaryDB, attachSql, NULL, NULL, NULL);
//将old_diary.db中task_table表中的数据,
//插入至diary.db的task_table表中
sqlite3_stmt *statement;
NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO task_table SELECT * FROM OldDiaryDB.task_table"];
int success = sqlite3_prepare(self.diaryDB, [insertSql UTF8String], -1, &statement, NULL);
if( success != SQLITE_OK ){
NSLog(@"插入数据失败");
}
//执行
success = sqlite3_step(statement);
//释放statement
sqlite3_finalize(statement);
if( success == SQLITE_ERROR ){
NSLog(@"失败");
}
else{
NSLog(@"成功");
}
//分离附加的数据库
sqlite3_exec(diaryDB, "DETACH DATABASE OldDiaryDB;", NULL, NULL, NULL);
}
sqlite3_close(diaryDB);
}
- (NSString*)getDBPathByName:(NSString*)name{
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
if( [paths isKindOfClass:[NSArray class]] && paths.count ){
return [paths[0] stringByAppendingPathComponent:name];
}
return nil;
}
网友评论