一、前言
二、需求
方法一:使用sqlitemanager建立資料庫和表,并将建立好的資料庫檔案拖入項目中,最後調用以下代碼将資料庫複制到documents目錄;
/**
* 将資料庫檔案複制進沙盒
*/
-(void)createeditablecopyofdatabaseifneeded
{
// 先判斷 sandbox 下面的 documents 子檔案夾裡面有沒有資料庫檔案 test.sqlite
nsfilemanager *filemanager = [nsfilemanager defaultmanager];
nserror *error;
nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes);
nsstring *documentsdirectory = [paths objectatindex:0];
nsstring *writabledbpath = [documentsdirectory stringbyappendingpathcomponent:@"test.sqlite"];
bool iffind = [filemanager fileexistsatpath:writabledbpath];
if (iffind)
// nslog(@"資料庫已存在");
return;
}
else{
nslog(@"資料庫不存在,需要複制");
// 如果不存在資料庫檔案,則複制資料庫檔案
nsstring *defaultdbpath = [[nsbundle mainbundle] pathforresource:@"test" oftype:@"sqlite"];
bool ifsuccess = [filemanager copyitematpath:defaultdbpath topath:writabledbpath error:&error];
if (!ifsuccess) {
nslog(@"failed to create writable database file with message '%@'.", [error localizeddescription]);
}else {
nslog(@"createeditablecopyofdatabaseifneeded 初始化成功");
方法二:利用開源的fmdb庫代碼建立資料庫;
* 代碼建立資料庫
- (void)createdatabaseifneeded
// 資料庫路徑
nsstring *doc = [paths objectatindex:0];
nsstring *path = [doc stringbyappendingpathcomponent:@"test.sqlite"];
nsfilemanager * filemanager = [nsfilemanager defaultmanager];
if ([filemanager fileexistsatpath:path] == no) {
// create it
fmdatabase * db = [fmdatabase databasewithpath:path];
if ([db open]) {
// 建立user表
nsmutablestring *sql = [nsmutablestring stringwithformat:@"%@",@"create table user"];
[sql appendstring:@"("];
[sql appendstring:@"username varchar,"];
[sql appendstring:@"password varchar"];
[sql appendstring:@")"];
bool res = [db executeupdate:sql];
if (!res) {
debuglog(@"error when creating table user");
} else {
debuglog(@"succ to creating table user");
[db close];
else {
debuglog(@"error when open db");
注:fmdb庫使用教程http://blog.devtang.com/blog/2012/04/22/use-fmdb/
三、總結
1、第一種方法建立資料庫在需求變動的情況下(如增加幾張表)容錯率稍高,推薦使用第一種方法;
2、兩種方法均是先判斷資料庫是否存在然後再決定要不要建立/複制資料庫。在一種特殊情況下-應用更新版本,其實原來的資料庫檔案是會從老的版本中拷貝到新版本中(參考:http://blog.csdn.net/zyx586/article/details/18989199),是以更新版本後資料庫檔案是不會做任何改變的,就算你在新的版本中完全改變資料庫的結構。是以如果存在資料庫變動的需要在應用版本更新後重新建立一個全新的資料庫并備份舊的資料;
最新内容請見作者的github頁:http://qaseven.github.io/