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 = [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
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.