【问题标题】:Android SQLite "BETWEEN" not inclusive or returns all recordsAndroid SQLite“BETWEEN”不包含或返回所有记录
【发布时间】:2012-01-31 12:55:50
【问题描述】:

看起来非常简单的任务,尝试在 Android 应用程序中的我的 SQLite 数据库中获取给定范围的记录/行:

String[] projection = {"_id"};
String selection = "_id between ? and ?";
String[] selectionArgs = {"1", "10"};

queryBuilder.query(db, projection, selection, selectionArgs, null, null, null);

通过上面的 selectionArgs,我只得到了两行,第 1 行和第 10 行。如果我将 arg 更改为其他任何内容,我将得到整个批次(整个记录/行集),就好像没有条件一样。一天以来一直在敲我的脑袋,为什么它会以这种方式工作,也许关于在 SQLite 中使用“between”有一些特别的事情需要了解?非常感谢任何 cmets/帮助。

【问题讨论】:

    标签: android sqlite between


    【解决方案1】:

    您可以使用此代码。

    private SQLiteDatabase productDatabase;
       public Cursor get_result(){
       Cursor c;
       String sql = "SELECT * FROM " + tableName +"WHERE _id BETWEEN" + value1 +"AND" + value2;
       c = productDatabase.rawQuery(sql, null);
    }
    
    Cursor cursor=get_result();
        if(cursor.moveToNext()){
        Log.d("count of product id="+cursor.getString(0));
    }
    

    【讨论】:

      【解决方案2】:

      我检查过你那边似乎有问题,它工作正常,

      方法

      public Cursor GetBetween(String[] projection,String selection, String[] args){
              return db.query(TBL_NAME, projection, selection, args, null, null, null);
          }
      

      实施

              String[] projection = new String[]{"_id"};
              String[] selectionArgs = new String[]{"1","3"};
              String selection = "_id between ? and ?";
              Cursor cursorGetBetween = helper.GetBetween(projection,selection, selectionArgs);
              startManagingCursor(cursorGetBetween);
              cursorGetBetween.moveToFirst();
              while(!cursorGetBetween.isAfterLast()){
                  Log.d("value of cursorGetBetween", cursorGetBetween.getString(0));
                  cursorGetBetween.moveToNext();
              }
      

      输出

      01-31 18:42:58.176: D/value of cursorGetBetween(647): 1
      01-31 18:42:58.176: D/value of cursorGetBetween(647): 2
      01-31 18:42:58.176: D/value of cursorGetBetween(647): 3
      

      【讨论】:

      • 我需要从查询中返回 Cursor 以填充列表。是的,我也尝试并使用了 SQLiteDatabase 的 query 和 rawQuery 方法,两者的精确结果与我最初的问题相同。
      • 哦,伙计..这只会让它更加神秘..我试图实际检查我的光标返回了多少结果,希望它显示结果的方式有一些错误,但是它证实了我的初步结果。我不知道它为什么会发生..使用上面的代码..
      • 好的,解决了!对于任何遇到此问题并想知道为什么...对于“介于”和很可能所有类似的按索引工作的分组查询的迷失灵魂,数据库实际上需要具有约束和相应的序列表...我的是在外部创建的SQLite DB 浏览器,其中包含从 CSV 文件导入的表,而不是从 SQL 执行中导入的表。祝大家好运!
      猜你喜欢
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多