1

大家好,我对 ios 中的 sqlite 不太了解。我正在使用查询来搜索单词/句子。下面是我检索记录的示例代码

        -(NSArray *)prepareSearchResultsForQuery:(NSString *)searchString{

        searchQueryString = searchString;

        sqlite3_stmt *searchResultsStmt;
        NSMutableArray *arrayOfSearchResults;
       NSString *searchResultsQuery = [NSString stringWithFormat:@"SELECT * FROM Search WHERE pageText LIKE '%%%@%%'",searchString];
        if (sqlite3_prepare_v2(bookDB,[searchResultsQuery UTF8String],-1,&searchResultsStmt,nil) == SQLITE_OK) {
            arrayOfSearchResults = [[NSMutableArray alloc]initWithCapacity:1];

            while (sqlite3_step(searchResultsStmt) == SQLITE_ROW) {
                XPathSearchResult *xpathObj = [[XPathSearchResult alloc] init];
                xpathObj.targetPageIndex = sqlite3_column_int(searchResultsStmt, 2);
                NSString *entirePageString = [[[NSString alloc] initWithUTF8String:(const char*)sqlite3_column_text(searchResultsStmt, 4)] autorelease];
                xpathObj.stringContainingSearchQuery = [self getDisplayStringFromPageString:entirePageString];

                [arrayOfSearchResults addObject:xpathObj];
                [xpathObj release];

            }
        }
        sqlite3_finalize(searchResultsStmt);
        return arrayOfSearchResults; 
    }
    }

上面的代码对我有用,直到有类似地球的词

如果单词包含 '"" < 字符我的方法不起作用。现在我发现我们需要使用准备好的语句来摆脱这个问题。任何人都可以建议我在这种情况下如何使用准备好的语句。提前致谢

4

1 回答 1

0

该应用程序正在崩溃,因为您有未转义的转义字符(在本例中为单引号)。添加这一行:

[sqlQuery stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];

应该防止由单引号引起的崩溃。您还可以创建一个正则表达式来删除所有此类字符的转义。

于 2012-09-05T13:33:42.883 回答