2012-04-11 79 views
3

要使用sqlite將數據插入數據庫,需要複製數據庫以使其可寫。所以,我有我的類此方法,每一個建議,我已經看到在堆棧溢出和許多其他網站:iOS - FMDB數據庫插入

-(void)createEditableCopyOfDatabaseIfNeeded 
{ 
    BOOL success; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"sample.db"]; 

    success = [fileManager fileExistsAtPath:writableDBPath]; 

    if (success) return; 
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.db"]; 
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
     if (!success) { 
      NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
     } 

} 

當然,我有這下代碼來訪問我的數據庫:

FMDatabase *db; = [FMDatabase databaseWithPath:[[NSBundle mainBundle] pathForResource:@"sample" ofType:@"db"]]; 
if (![db open]) { 
    NSLog(@"Error!"); 
} 
else { 
    NSLog(@"Database opened!!"); 
} 

[self createEditableCopyOfDatabaseIfNeeded]; 
[db executeUpdate:@"Insert into user (name, phone, comment) values(?, ?, ?)", @"Name1", @"13548", @"This is a comment", nil]; 
NSLog(@"Inserted"); 

FMResultSet *s = [db executeQuery:@"SELECT * FROM user"]; 
while ([s next]) { 
    NSLog(@"%@", [s stringForColumn:@"comment"]); 
} 

現在,我有幾個問題:

  1. 插入代碼在執行/運行時在模擬器中完美工作。但是,這對真實的sample.db沒有影響,我認爲它必須在我的Mac硬盤驅動器中有一個可寫的副本。這是可以接受的。但是當我在iPhone上運行這些代碼時,它有點不識別我的createEditableCopyOfDatabaseIfNeeded方法,並給出了此錯誤:Unknown error finalizing or resetting statement > (8: attempt to write a readonly database)。如何使用FMDB使這些代碼正常工作?

  2. 在iPhone上運行時,被複制的數據庫位於何處?複製後,即使沒有連接到我的Mac,iPhone是否再次使用該數據庫?

我在設備上運行時無法插入某些東西。 請幫忙。

非常感謝!

+0

1.您不能編輯/更新/更改AppBundle中的文件,您需要在文檔目錄中創建數據庫。 – CarlJ 2012-04-11 10:56:25

+0

是的,我建議使用FMDatabase或CoreData(事件更好)與SQLite – CarlJ 2012-04-12 08:53:15

回答

5

,如果你正在讀這篇文章,那麼我有解釋你的問題。

  1. 如果在資源包的任何文件,那麼它是一個只讀文件。因此,您的資源目錄的數據庫路徑僅供閱讀之用。

  2. 根據您編寫的複製數據庫的代碼,將在您的應用程序的文檔目錄中創建數據庫。即使從Mac中刪除iPhone,該路徑也不會受到影響。

0

嘗試這種在數據庫中插入

[db open]; 

FMResultSet *results = [db executeQueryWithFormat:@"SELECT cms_desc FROM cms_media where cms_name=%@",@"name"]; 

NSString *str; 

while([results next]) 

{ 

    str=[results stringForColumn:@"cms_desc"]; 
} 

[results close]; 

[db close]; 

只需將你項目,請在.sqlite文件和應用程序重設在設備

+1

謝謝,但你太遠我的朋友,太遠了。 – ruelluna 2012-04-11 11:13:22