Insert iOS database - FMDB

To insert data into a database using sqlite, copying the database is required to make it writable. So I have this method in my class, every sentence I saw over stack overflow and many other sites:

-(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]);
        }

}

Of course, I have the following codes to access my database:

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"]);
}

Now I have a few questions:

  • The embed code worked fine in the simulator on run / run. However, this did not affect the real sample.db, which, as I understand it, should have a recordable copy somewhere on my mac's hard drive. It is acceptable. But when I run this code on the iphone, it is somewhat not recognize my method createEditableCopyOfDatabaseIfNeededand gave this error: Unknown error finalizing or resetting statement > (8: attempt to write a readonly database). How to make these codes work using FMDB?

  • iPhone, ? iPhone , mac?

- . , .

!

+3
2

, .

  • , READ-ONLY. , .

  • , , . , iPhone Mac.

+5

[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 reset

0

All Articles