Question

I'm developing for iOS and I have a previous database really poorly constructed. Now there is already 140 sealed but in my update I make a new database but I can not delete the data... How can I change the data from database A to database B ? I use sqlite3 in xCode 5

Was it helpful?

Solution

Here is an example code altering a column in a database table:

- (void)alterDB {

    sqlite3_stmt *statement;
    sqlite3_stmt *selectStmt;

    const char *columnExists = "select callCount from lastCall";
    //Alter the table ONLY IF column we want doesn't exist
    if (sqlite3_prepare_v2(database, columnExists, -1, &selectStmt, NULL) != SQLITE_OK)
    {
        NSString *updateSQL = [NSString stringWithFormat:@"ALTER TABLE lastCall ADD COLUMN callCount INTEGER"];
        const char *update_stmt = [updateSQL UTF8String];
        sqlite3_prepare_v2(database, update_stmt, -1, &statement, NULL);

        if (sqlite3_step(statement) == SQLITE_DONE) {
            NSLog(@"DATABASE ALTERED");
        } else {
            NSLog(@"error altering database");
        }
    }

}

I hope this gives you an idea.

OTHER TIPS

Write migration code, that will select the data from Database A and will insert it into Database B.

When dealing with different schemas, I have a method that I always call when opening the database that checks the schema version in a table set aside for that purpose and then doing any alterations as needed to the schema.

- (void) checkSchema {
    if([[self preferenceForKey:@"SchemaVersion"] isEqualToString: @"1"]) {
        [db sqlExecute:@"create table Documents(documentID int, description text, type text, url text, modifiedDate text, read int, fileName text, needsUpdate int, primary key(documentID,type));"];
        [self setPreference:@"2" ForKey:@"SchemaVersion"];
    }

    // etc. 
}

So while developing, I can add schema changes and no matter what version of the app someone is using, when they upgrade they will get the latest schema changes.

It is because of this, and the work of changing all my accessor methods to the database that I am now using SimpleDB (https://github.com/AaronBratcher/SimpleDB), a key/value db I wrote. Completely different way of accessing data that makes things a lot simpler.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top