【问题标题】:Filtering query in database SQLite在数据库 SQLite 中过滤查询
【发布时间】:2011-08-22 08:49:21
【问题描述】:

我在数据库中有一个表,我想只显示该表的一行。该表有 3 个字段(ID、标题和描述)。 我想根据标题过滤行。

我有这个代码:

Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null, ORDER_BY);

其中第三个字段是选择项(字符串)。但我不知道我必须准确地选择我想要显示的行。谢谢

【问题讨论】:

    标签: android sqlite filtering


    【解决方案1】:

    试试这个

    Cursor cursor = db.query("TABLE_NAME",new String[]{"ColumnName"}, "ColumnName=?",new String[]{"value"}, null, null, null);
    

    【讨论】:

    • 我只是想尝试选择一行或其中一些,而不是显示所有表格。例如我想显示带有标题的行:TITLE=test
    【解决方案2】:
    String[] FROM = { // ID of the column(s) you want to get in the cursor
            ID,
            Title,
            Description 
    };
    
    String where = "Title=?"; // the condition for the row(s) you want returned.
    
    String[] whereArgs = new String[] { // The value of the column specified above for the rows to be included in the response
            "0" 
        };
    
    return db.query(TABLE_NAME, FROM, where, whereArgs, null, null, null);
    

    这应该会给你一个包含所有列的光标,但只包含 Title 列的值等于 0 的行。

    【讨论】:

    • @user736605 不要忘记将其标记为已接受的答案。 :) 点击它旁边的复选标记。
    • @TofferJ,你是说这里的Title还是Table“其中Table列的值等于0”!
    • @MazenKasser:这是 Title 列的值。 :) 没有其他的。感谢您指出了这一点。我已经编辑了我的答案。
    【解决方案3】:

    您可以在SQLite中通过以下代码进行搜索;

    在 MainActivity 中;

    search.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s.toString());
        }
    });
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return 
    //Here you can filter data by any row , just change text replace of "subject"
    dbManager.fetchdatabyfilter(constraint.toString(),"subject");
        }
    });
    

    DatabaseHelper.java

    public Cursor fetchdatabyfilter(String inputText,String filtercolumn) throws SQLException {
    Cursor row = null;
    String query = "SELECT * FROM "+DatabaseHelper.TABLE_NAME;
    if (inputText == null  ||  inputText.length () == 0)  {
        row = database.rawQuery(query, null);
    }else {
        query = "SELECT * FROM "+DatabaseHelper.TABLE_NAME+" WHERE "+filtercolumn+" like '%"+inputText+"%'";
        row = database.rawQuery(query, null);
    }
    if (row != null) {
        row.moveToFirst();
    }
    return row;
     }
    

    【讨论】:

      猜你喜欢
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      相关资源
      最近更新 更多