2

以下は私のdb関数です:

+(NSArray*)searchWithKey:(NSString*)_key{
NSMutableArray* tmpArray = [NSMutableArray array];
static Statement* stmt = nil;
char* sql = "select * from Bookmarks where BMUrl like '%?%'";
if (stmt == nil) {
    stmt = [DBConnection statementWithQuery:sql];
    [stmt retain];
}
[stmt bindString:_key forIndex:1];
while ([stmt step] == SQLITE_ROW) {
    BookMark* tmpBM = [[BookMark alloc] initWithStatement:stmt];
    NSLog(@"tmpBM = %@",tmpBM);
    [tmpArray addObject:tmpBM];
    [tmpBM release];
}
[stmt reset];
return tmpArray;}

SQL のキーワードは、私が使用する「like」ですが、sqlite が返す結果はありません。SQL を「select * from Bookmarks where BMUrl like '%h%'」に変更すると、いくつかの結果が返されます。したがって、関数「bindString:forIndex」が間違いだと思います。コードは次のとおりです。

- (void)bindString:(NSString*)value forIndex:(int)index{
sqlite3_bind_text(stmt, index, [value UTF8String], -1, SQLITE_TRANSIENT);}

私が使用する正しい sqlite3 api はどれですか? ありがとう!

4

1 に答える 1

1

バインディングはそのように補間されません。のように文字列に引用符を入れる'%?%'と、文字どおりの疑問符として解釈されます。

代わりに入力を変更する必要があります_key:

  • %andのインスタンスをエスケープ_する\
  • %先頭と末尾に s を追加します

これにより、LIKEオペレーターで使用する準備が整います。

?また、 がスタンドアロン パラメータを表すように SQL を変更する必要があります: ... where BMUrl like ?


%特殊文字をエスケープし、 の先頭と末尾に s を追加する方法の例を次に示します_key

NSString *escapedKey = [_key stringByReplacingOccurencesOfString:@"%" 
                                                      withString:@"\\%"];
escapedKey = [escapedKey stringByReplacingOccurencesOfString:@"_"
                                                  withString:@"\\_"];
NSString *keyForLike = [NSString stringWithFormat:@"%%%@%%", escapedKey];
[stmt bindString:keyForLike forIndex:1];
于 2013-01-26T03:17:05.453 に答える