Search code examples
objective-csqlitestringwithformat

What's the correct way to escape sqlite format specifiers in a string


What's the correct way to escape sqlite format specifiers in a string?

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];

    NSDate *today = [NSDate date];
    NSString *todaysDate = [dateFormatter stringFromDate:today];

    NSString *SQL = [NSString stringWithFormat: @"SELECT id,strftime(\"%Y-%m-%d\") as `date`,word,term FROM words WHERE `date` <= '%@' ORDER BY `date` DESC LIMIT 1",todaysDate];

Thanks


Solution

  • Figured it out. To escape "%", use "%%".

    NSString *SQL = [NSString stringWithFormat: @"SELECT id,strftime(\"%%Y-%%m-%%d\") as `date`,word,term FROM words WHERE `date` <= '%@' ORDER BY `date` DESC LIMIT 1",todaysDate];