sqliteを使用してデータベースにデータを挿入するには、データベースをコピーして書き込み可能にする必要があります。今iOS - FMDBデータベースの挿入
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"]);
}
:もちろん
-(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]);
}
}
私は私のデータベースにアクセスするには、この次のコードを持っています。だから私は、私は、スタックオーバーフローや他の多くのサイト上で見てきたすべての提案は私のクラスでは、このメソッドを持っています
実行時に挿入コードが完全に機能し、実行されました。しかし、これは私のMacのハードドライブのどこかに書き込み可能なコピーがなければならないと結論づけた実際のsample.dbには影響しませんでした。それは容認できるものです。しかし、私はこれらのコードをiphoneで実行したときに、私の
createEditableCopyOfDatabaseIfNeeded
メソッドが認識されず、Unknown error finalizing or resetting statement > (8: attempt to write a readonly database)
というエラーが出ました。 FMDBを使用してこれらのコードを動作させるにはどうすればよいですか?iPhoneで実行している場合、コピーされるデータベースはどこにありますか?コピーした後、iPhoneは私のMacに接続していなくても、そのデータベースを再び使用しますか?
デバイスで実行したときに何かを挿入できません。 助けてください。
ありがとうございました!
1.ドキュメントディレクトリにdbを作成する必要があるAppBundle内のファイルを編集/更新/変更することはできません。 – CarlJ
はい、SQLite – CarlJ