使用Objective C在数据库条目中搜索String

时间:2014-09-13 10:18:56

标签: ios objective-c sqlite uisearchbar uisearchbardelegate

我试图在搜索栏中搜索用户输入的文本,以检查该文本是否包含在任何数据库条目中,并希望将结果存储到 NSMutableArray < / p>

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [search resignFirstResponder];
    [search endEditing:YES];

    str = search.text;

    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    app.databasePath = [app getDBPath];
    const char *dbpath = [app.databasePath UTF8String];
    sqlite3_stmt *statement;

    if (sqlite3_open(dbpath, &conn) == SQLITE_OK)
    {
        NSString *strSelectQuery = [NSString stringWithFormat: @"SELECT songname FROM Songs WHERE songname LIKE '%%@%'", str];

        const char *query_stmt = [strSelectQuery UTF8String];

        if (sqlite3_prepare(conn, query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            while (sqlite3_step(statement) == SQLITE_ROW)
            {
                [matchList addObject:[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]];
            }
            sqlite3_finalize(statement);
        }
        sqlite3_close(conn);
    }
    NSLog(@"Total Songs : %i", [matchList count]);
}

1 个答案:

答案 0 :(得分:0)

上面的代码没有用,因为我忘记写了一行,在我输入文本并点击UISEarchBar的搜索按钮后重新加载数据

[_ searchResultTable reloadData];

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [search resignFirstResponder];
    [search endEditing:YES];

    str = search.text;

    songList = [[NSMutableArray alloc] init];

    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    app.databasePath = [app getDBPath];
    const char *dbpath = [app.databasePath UTF8String];
    sqlite3_stmt *statement;

    if (sqlite3_open(dbpath, &conn) == SQLITE_OK)
    {
        NSString *strSelectQuery = [NSString stringWithFormat: @"SELECT * FROM Songs WHERE songname LIKE '%%%@%%'", str];
        const char *query_stmt = [strSelectQuery UTF8String];

        if (sqlite3_prepare(conn, query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            while (sqlite3_step(statement) == SQLITE_ROW)
            {
                [songList addObject:[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]];
            }
            sqlite3_finalize(statement);
        }
        sqlite3_close(conn);
    }

    [_searchResultTable reloadData];
}