2012-04-26 31 views
4

私はfmdbを使用していますが、dbファイルを追加する場所がわかりません。 this old answer私はそれがxcode 4.2には合っていないと思っています(私たちはもう 'Resources'フォルダを持っていないので)。既存のデータベースfmdbを開くにはどうすればいいですか?

私は、 'リタ' でデータベースを作成した拡張.sqliteを追加し、次のようにDBファイルを追加しました:

dbsqlite

は、私は、次の

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docsPath = [paths objectAtIndex:0]; 
NSString *path = [docsPath stringByAppendingPathComponent:@"db.sqlite"]; 
FMDatabase *database = [FMDatabase databaseWithPath:path]; 
[database open]; 
FMResultSet *results = [database executeQuery:@"select * from tbl"]; 
printf("hi"); 
while([results next]) { 
    printf("hi2"); 
NSString *name = [results stringForColumn:@"clm1"]; 
NSString *text = [results stringForColumn:@"clm2"];   
NSLog(@"test: %@ - %@",name, text); 
} 
printf("done"); 

を使用しようとしました「ハイ」を「完了」しても「ハイ2」を決してしないでください...

誰でも助けることができますか?

答えて

6

(コンパイルされた)データベースをリソースとしてプロジェクトに追加して、最初の起動時にアプリケーションのドキュメントフォルダにコピーします。

ここでは、作業を行い、applicationDidFinishLaunchingから呼び出して、結果のFMDatabase *をすべてのクエリに使用するメソッドの例を示します。

- (FMDatabase *)openDatabase 
{ 
    NSFileManager *fm = [NSFileManager defaultManager]; 
    NSString *documents_dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    NSString *db_path = [documents_dir stringByAppendingPathComponent:[NSString stringWithFormat:@"database.s3db"]]; 
    NSString *template_path = [[NSBundle mainBundle] pathForResource:@"template_db" ofType:@"s3db"]; 

    if (![fm fileExistsAtPath:db_path]) 
     [fm copyItemAtPath:template_path toPath:db_path error:nil]; 
    FMDatabase *db = [FMDatabase databaseWithPath:db_path]; 
    if (![db open]) 
     NSLog(@"Failed to open database!"); 
    return db; 
} 
+0

感謝。リソースを追加する場所を教えてくれますか? AppDelegate.hまたは他のディレクトリと同じディレクトリにありますか?どこに? – iosMentalist

+0

拡張子 '.sqlite'をファイルに追加するべきではありません。違いはなんですか?私はちょうどexentionlessを残す必要がありますか?それは非論理的です!とにかく私はHampusの提案を使用しました...ありがとう – iosMentalist

+0

.sqliteは、データベースを作成するSQLクエリステートメントを含むファイルですが、コンパイルされたデータベースは通常.s3db拡張子を持ちます。 "sqlite3 database.s3db

1

私は現在同じ問題を扱っています。しかし、あなたの質問に答えるには:ドキュメントフォルダは、デバイスで使用されるフォルダです。

データベースをサポートファイルフォルダに配置します。ここで

は私のためにどのような作品です:

//hide status bar for full screen view 
[[UIApplication sharedApplication]setStatusBarHidden:YES   withAnimation:UIStatusBarAnimationNone]; 

//set reference to database here 
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
      NSString *documentDir = [documentPaths objectAtIndex:0]; 
      self.databasePath = [documentDir stringByAppendingPathComponent:@"RPRA.sqlite"]; 

    [self createAndCheckDatabase]; 

    // Override point for customization after application launch. 
    return YES; 
} 

//method used to create database and check if it exists 

-(void) createAndCheckDatabase 
{ 
    BOOL success; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    success = [fileManager fileExistsAtPath:self.databasePath]; 

    if(success) return; 

    //else move database into documents folder 
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] 
            stringByAppendingPathComponent:@"RPRA.db"]; 

    [fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil]; 
} 
+0

また、XCodeは、使用するSQLまたはSQLiteファイルにかなり敏感であることを指摘したいと思います。あなたのアプリケーションにSQLファイルを読み込ませるのに問題がある場合(例えば、すべてのテーブルで列にエラーが見つからないなど)、Firefox SQLite Managerツールが追加のメタテーブルを追加していないことを確認してください。コマンドAを実行してFirefoxのSQLite ManagerのSQL実行セクションに貼り付け、sqlを実行することによって、別のデータベースにデータベースを再作成する必要がありました。これにより、XCodeがメタテーブルなしで読める新しいデータベースが作成されました。 –

0
- (void)ensureDBFile 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *dbFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"retails.sqlite"]]; 

    NSLog(@"Database Filepath Delgate = %@", dbFilePath); 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    BOOL dbFileExists = [fileManager fileExistsAtPath:dbFilePath]; 

    if(!dbFileExists){ 
     //Copy the db file if it didn't exist 
     NSString *bundledDbPath = [[NSBundle mainBundle] pathForResource:@"retails" ofType:@"sqlite"]; 

     if (bundledDbPath != nil) { 
      BOOL copiedDbFile = [fileManager copyItemAtPath:bundledDbPath toPath:dbFilePath error:nil]; 
      if (!copiedDbFile) { 
       NSLog(@"Error: Couldn't copy the db file from the bundle"); 
      } 
     } 
     else { 
      NSLog(@"Error: Couldn't find the db file in the bundle"); 
     } 
    } 
    self.db = [FMDatabase databaseWithPath:dbFilePath]; 
    [self.db setShouldCacheStatements:NO]; 
    [self.db open]; 
    if([self.db hadError]) { 
    NSLog(@"Database Error %d: %@", [self.db lastErrorCode], [self.db lastErrorMessage]); 
    } 
} 
関連する問題