mercredi 4 novembre 2015

iOS insert table data from one database to another in SQLite

Hi I am trying to move one database table data to another database table, both table have the same column names. I am using the Sqlite Attache statement and adding the older database and using the below objective-c code for copying data but code works fine and it gets failed when it executes the insert query. not sure but issue seems to be in SQLite Connection.

-(void)insertDataFromOldDBtoNew
{
NSString* newDbPath;
NSString* oldDbPath;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
newDbPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"file.sqlite"]];
oldDbPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"file-old.sqlite"]];
sqlite3 *db = [self OldDatabase];

//open database which contains the desired "table"
if (sqlite3_open(newDbPath.UTF8String, &db) == SQLITE_OK)
{
    NSString *attachSQL = [NSString stringWithFormat: @"ATTACH DATABASE \"%@\" AS phase2_db",oldDbPath];

    const char *attachSQLChar = [attachSQL UTF8String];
    char* errInfo;
    int result = sqlite3_exec(database, attachSQLChar, nil, nil, &errInfo);

    if (SQLITE_OK == result)
    {
        NSLog(@"new db attached");

        NSString *attachSQL = [NSString stringWithFormat: @"Insert into car select * from phase2_db.car"];

        const char *createSQLChar = [attachSQL UTF8String];
        int result2 = sqlite3_exec(database, createSQLChar, nil, nil, &errInfo);

failing here--geting result2 as 1

        if (SQLITE_OK == result2)
        {
            NSLog(@"New table created in attached db");
        }
    }

    sqlite3_close(database);
}
}

Aucun commentaire:

Enregistrer un commentaire