2010-11-17 164 views
1

在我的iPhone應用程序中,我要求搜索SQLite數據庫。使用SQLite「like」子句查找類似詞語的SQLite查詢

我會根據用戶輸入文本框的內容搜索相似的數據。

我想要什麼:

我想查詢像

選擇categorytable哪裏像 'A%',類別,如果用戶輸入

我試圖

NSString *query = [NSString stringWithFormat:@"Select category from categorytable where category like '%@%'",textbox1.text]; 
類別

它沒有顯示在輸入字符後的「%」 e用戶。

在控制檯它顯示像

**Select category from categorytable where category like 'A'** which is incorrect 

應該用什麼查詢?

回答

2

你需要在stringWithFormat中使用%%。

+0

謝謝約瑟夫! :] – 2010-11-17 08:37:36

2

字符串格式說明符文檔說,如果您希望%文字字符出現在最終字符串中,則應在格式字符串中使用%%。所以你應該使用'%@%%'

0

正如其他人所說的,在stringWithFormat中使用%%語法使文字百分號出現在搜索字符串中。但是,不要使用你的SQL。只有用價值來做那件事。應避免使用stringWithFormat將文本值直接插入到SQL中。相反,使用?佔位符在SQL:

NSString *value = [NSString stringWithFormat:@"%@%%", textbox1.text]; 

NSString *query = @"Select category from categorytable where category like ?"; 

然後你sqlite3_stmt使用query,然後用valuesqlite3_bind_text準備。例如:

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); 
} 

或者,如果使用FMDB:

FMResultSet *rs = [db executeQuery:query, value]; 
NSAssert(rs, @"%@", [db lastErrorMessage]); 

while ([rs next]) { 
    NSLog(@"%@", [rs resultDictionary]); 
} 
[rs close]; 

這一點很重要,以防止值內的'人物的出現而引起的問題(例如,如果你正在尋找「 Bob's Bar and Grill「)。