[英]SQLite query for finding similar words using the SQLite “like” clause
In my iPhone app, I have requirement to search the SQLite database. 在我的iPhone应用程序中,我需要搜索SQLite数据库。
I will search the similar data on the basis of what the user enters into the textbox. 我将根据用户输入文本框的内容搜索类似的数据。
What I want: 我想要的是:
I want query like 我想要查询
Select category from categorytable where category like 'A%' , if user enters A 如果用户输入A, 则从类别表中选择类别,如'A%'
I tried 我试过了
NSString *query = [NSString stringWithFormat:@"Select category from categorytable where category like '%@%'",textbox1.text];
It does not show the "%" after the character entered by the user. 在用户输入的字符后,它不显示“%”。
In console it shows like 在控制台中,它显示为
**Select category from categorytable where category like 'A'** which is incorrect
What should be the query? 该查询应该是什么?
The string format specifiers document says that if you want the %
literal character to appear in the final string, you should use %%
in the format string. 字符串格式说明符文档说如果您希望%
literal字符出现在最终字符串中,则应在格式字符串中使用%%
。 So you should be using '%@%%'
所以你应该使用'%@%%'
您需要在stringWithFormat中使用%%。
As others have said, use %%
syntax in stringWithFormat
to have the literal percent sign appear within the search string. 正如其他人所说,在stringWithFormat
使用%%
语法使文字百分号出现在搜索字符串中。 But, do not do that with your SQL. 但是,不要用你的SQL做到这一点。 Only do that with the value. 只有价值才能做到这一点。 One should avoid using stringWithFormat
to insert text values directly into the SQL. 应该避免使用stringWithFormat
将文本值直接插入SQL。 Instead, using ?
相反,使用?
placeholders in the SQL: SQL中的占位符:
NSString *value = [NSString stringWithFormat:@"%@%%", textbox1.text];
NSString *query = @"Select category from categorytable where category like ?";
Then prepare your sqlite3_stmt
using query
and then sqlite3_bind_text
with the value
. 然后使用query
准备sqlite3_stmt
,然后使用value
sqlite3_bind_text
准备。 For example: 例如:
sqlite3_stmt *statement;
int rc;
if ((rc = sqlite3_prepare_v2(db, [query UTF8String], -1, &statement, NULL)) != SQLITE_OK) {
NSLog(@"%s (%ld)", sqlite3_errmsg(db), (long)rc);
} else {
if ((rc = sqlite3_bind_text(statement, 1, [value UTF8String], -1, SQLITE_TRANSIENT)) != SQLITE_OK) {
NSLog(@"%s (%ld)", sqlite3_errmsg(db), (long)rc);
}
while ((rc = sqlite3_step(statement)) == SQLITE_ROW) {
const unsigned char *string = sqlite3_column_text(statement, 0);
NSLog(@"%s", string);
}
if (rc != SQLITE_DONE) {
NSLog(@"%s (%ld)", sqlite3_errmsg(db), (long)rc);
}
sqlite3_finalize(statement);
}
Or, if using FMDB: 或者,如果使用FMDB:
FMResultSet *rs = [db executeQuery:query, value];
NSAssert(rs, @"%@", [db lastErrorMessage]);
while ([rs next]) {
NSLog(@"%@", [rs resultDictionary]);
}
[rs close];
This is important, to prevent problems stemming from the occurrences of '
characters within the value (eg, if you're looking for "Bob's Bar and Grill"). 这一点非常重要,可以防止因价值中出现'
人物'
而产生的问题(例如,如果您正在寻找“Bob's Bar and Grill”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.