Search code examples
iosxcodesqlitefmdb

How to selectively replace sqlite row?


In my case 2 I am trying to replace the later sqlite entry for the qrcode. I want to update the row with a new FBid. How do I select it and then replace it? Is it something to do with sqlite? or is there some logic I need to apply within my app?

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:@"easyKTDB.sqlite"];

FMDatabase *database = [FMDatabase databaseWithPath:path];

[database open];

FMResultSet *results = [database executeQuery:@"select * from ktcode where code = ?;", qrCode];

while ([results next]) {
    ktcode *aktcode = [ktcode new];
    aktcode.ktCODE = [results stringForColumn:@"code"];
    aktcode.ktFBID = [results stringForColumn:@"fbid"];
    aktcode.uniqueID = [results intForColumn:@"id"];

    [ktcodeArray addObject:aktcode];

}

switch (ktcodeArray.count)
{
    case 0 :
        [database executeUpdate:@"insert into ktcode (code, fbid) values (?, ?)", qrCode, FBid];
        NSLog(@"%@ is now registered to %@ - %@", qrCode, userName, FBid);
        break;

    case 1:
        [database executeUpdate:@"insert into ktcode (code, fbid) values (?, ?)", qrCode, FBid];
        NSLog(@"%@ now belongs to %@ - %@", qrCode, userName, FBid);
        break;

    case 2:
        //[database executeUpdate:@""];
         NSLog(@"ktCodeArray: %@", ktcodeArray);
         NSLog(@"%@ has been transfered to %@ - %@", qrCode, userName, FBid);
        break;

    default :
        NSLog(@"Nothing else can be done");
        //delete multiple entries here

Solution

  • It seems you are looking for the REPLACE keyword in SQLite: https://www.sqlite.org/lang_replace.html

    If you have the unique identifier, then you can do:

    [database executeUpdate:@"replace into ktcode (id, code, fbid) values (?, ?, ?)", uniqueId, qrCode, FBid];