Objective-C sqlite adding query parameter inside of LIKE clause

假如想象 提交于 2019-12-23 10:06:38

问题


I am using sqlite in Objective-C via the C API. One of the intended features of my app is that the user can search for a person name and with each new character they enter, an SQL query using LIKE is executed to find all people whose names qualify as a match. The issue I am running into is parameterizing the match inside the LIKE, without the question mark being interpreted literally. That is, I believe the app at present is looking for people's names that include ? in them (which is nobody).

My code looks like this:

const char *sql = "SELECT rowid, name, email FROM person WHERE name LIKE '%?%'";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK) {
    NSLog(@"Problem preparing getFilteredPeopleStubs statement.");
}
if(sqlite3_bind_text(sqlStatement, 1, [searchText UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK){
    NSLog(@"Problem binding search text param.");
}

Basically, searchText is where I want the name to be coming from, but at the moment I believe it is just searching for people whose name contains ?, because of the single quotations in '%?%'. Is there a solution to this problem that still lets me use a parameterized query (protection against SQL injection) and achieves what I am after?


回答1:


Put the % characters into searchText, like (excuse the pun) this:

const char *sql = "SELECT rowid, name, email FROM person WHERE name LIKE ?";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK) {
    NSLog(@"Problem preparing getFilteredPeopleStubs statement.");
}
NSString *bindParam = [NSString stringWithFormat:@"%%%@%%", searchText];
if(sqlite3_bind_text(sqlStatement, 1, [bindParam UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK){
    NSLog(@"Problem binding search text param.");
}


来源:https://stackoverflow.com/questions/13357689/objective-c-sqlite-adding-query-parameter-inside-of-like-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!