开发者

INSERT OR REPLACE does not update the record in SQLITE

I am trying to insert the record in the database and whenever I do so, it inserts the record twice in the database. I am using the following query to do my insert:

-(void) insert {
      NSString *sqlQuery = [NSString stringWithFormat:@"INSERT OR REPLACE INTO test(ID,KEY ) VALUES ('%d','%@');", test.id, test.key];
      const char *insert_sql开发者_JS百科 = [sqlQuery UTF8String];
      sqlite3_exec(db, insert_sql, NULL, NULL, NULL);
}

It always enters duplicate records whenever I run this query. Is there a way to check if the data already exists then donot insert just update.


You're initializing the SQL string using stringWithFormat: but the string you pass is not a format string. The ? parameters are only recognized by the sqlite parser.

You can fix this either by replacing the SQL string with

// Assuming id is an int and key is a string
NSString *sqlQuery = [NSString stringWithFormat:@"INSERT OR REPLACE INTO test(ID,KEY ) VALUES (%d,%@);", test.id, test.key];

Or you need to call the sqlite prepare / bind functions to bind the parameters to the wildcards. For this see the prepare and bind documentation.

I suggest the second way, as this prevents SQL injection.


Is ID a primary key for the table, or otherwise indexed? It needs to be unique for a replacement to occur.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜