SomnusLee
SomnusLee

Reputation: 431

How to use an existed database file in Xcode, read and write?

I'm a bit new to Xcode and sqlite. Now I have a database file named "mydb.db", it already has some tables and datas. I put it on my mac folder and dragger it to my Xcode project under "Supporting Files".

Here is my code, but I find that I can only read from this "mydb.db", and cannot insert data to it! When I open "mydb.db" after execute my code by sqlite manager, I cannot find the data which should be inserted!

Who can tell me how to solve this problem? Thanks a lot!

NSString *dbFilePath = [[NSBundle mainBundle] pathForResource:@"mydb" ofType:@"db"];
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:dbFilePath]

    [queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"INSERT INTO Focus VALUES (?,?,?)" withArgumentsInArray:@[@"100000000",@2,@2]];

    }];

Upvotes: 3

Views: 3268

Answers (2)

FluffulousChimp
FluffulousChimp

Reputation: 9185

By adding the sqlite db file to your Supporting Files group in Xcode, you are just adding that file to the application's bundle so that during the build process it gets packaged with all of the other resources. Because the application can't write to its bundle, you must copy the sqlite database file from the bundle to a writable location, e.g.

#define FORCE_RECOPY_DB NO

- (void)copyDatabaseIfNeeded {
    NSFileManager *fm = [[NSFileManager alloc] init];
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *destinationPath = [documentsPath stringByAppendingPathComponent:@"pte.sqlite"];

    void (^copyDb)(void) = ^(void){
        NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"pte" ofType:@"sqlite"];
        NSAssert1(sourcePath, @"source db does not exist at path %@",sourcePath);

        NSError *copyError = nil;
        if( ![fm copyItemAtPath:sourcePath toPath:destinationPath error:&copyError] ) {
            DDLogError(@"ERROR | db could not be copied: %@", copyError);
        }
    };
    if( FORCE_RECOPY_DB && [fm fileExistsAtPath:destinationPath] ) {
        [fm removeItemAtPath:destinationPath error:NULL];
        copyDb();
    }
    else if( ![fm fileExistsAtPath:destinationPath] ) {
        DDLogInfo(@"INFO | db file needs copying");
        copyDb();
    }
}

Now when you wish to open the database, use the location in the documents path.

Note that you won't be able to inspect the sqlite db file in your project and expect to find the changes written from your code. (Since your code will now be working with the copied sqlite file.)

Upvotes: 2

Boggarapu
Boggarapu

Reputation: 333

First of all learn the tutorials of IOS.

its very simple.

const char *sqlStatement = "insert into Userprofile (Userauth, Age, , Year) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

then use sqlite3_prepare_v2 statement to execute that sqlStatement.

Upvotes: 1

Related Questions