要使用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"]);
}
現在,我有幾個問題:
插入代碼在執行/運行時在模擬器中完美工作。但是,這對真實的sample.db沒有影響,我認爲它必須在我的Mac硬盤驅動器中有一個可寫的副本。這是可以接受的。但是當我在iPhone上運行這些代碼時,它有點不識別我的
createEditableCopyOfDatabaseIfNeeded
方法,並給出了此錯誤:Unknown error finalizing or resetting statement > (8: attempt to write a readonly database)
。如何使用FMDB使這些代碼正常工作?在iPhone上運行時,被複制的數據庫位於何處?複製後,即使沒有連接到我的Mac,iPhone是否再次使用該數據庫?
我在設備上運行時無法插入某些東西。 請幫忙。
非常感謝!
1.您不能編輯/更新/更改AppBundle中的文件,您需要在文檔目錄中創建數據庫。 – CarlJ 2012-04-11 10:56:25
是的,我建議使用FMDatabase或CoreData(事件更好)與SQLite – CarlJ 2012-04-12 08:53:15