Search code examples
iossqliteinsert-updatealter-table

Alter Sqlite Database table and Update query for iOS


I have written SQLITE insert query to insert some data in sqlite database table. But now i am trying to add a new column in that sqlite table and inserting new values to that column. So that whenever i try to update my database table, it should create a new column every time and update and give me new values inserted. Here below is my alter and update code which i do on click of a button.

-(void)updateStatusData:(NSString *)txt {

sqlite3_stmt    *statement;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [docsDir stringByAppendingPathComponent:@"db.sqlite"];

NSLog(@"%@",databasePath);
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{



  NSString *updateSQL = [NSString stringWithFormat:@"ALTER TABLE STATUS ADD COLUMN newcolumn; UPDATE STATUS SET newcolumn=%@ WHERE rowid=1",txt];

    const char *update = [updateSQL UTF8String];
    NSLog(@"update statmnt %s",update);
    sqlite3_prepare_v2(database, update, -1, &statement, NULL);
    if (sqlite3_step(statement) == SQLITE_DONE)
    {
        sqlite3_bind_text(statement, 1, [txt UTF8String], -1, SQLITE_TRANSIENT);
        NSLog(@" Status Results Updated Successfully");

    } else {
        NSLog(@"error %s",sqlite3_errmsg(database));
    }
    sqlite3_finalize(statement);
    sqlite3_close(database);
}
}

My new column name is newcolumn and the values which it should save is in 'txt'. My question is whenever i run this code i get a new column inserted in my sqlite database table. But the value inserted is NULL for that newcolumn. The code should run just the way when you update your status on WHATSAPP, it saves the updated status... Please help me what wrong am i doing. Any help is appreciated.


Solution

  • Don't run both query together. make two seperate query one for add column and one for update the table. So run two different statement instead of one.