【问题标题】:How can I get the entire column from sqlite table using a cursor?如何使用游标从 sqlite 表中获取整个列?
【发布时间】:2014-11-11 20:39:02
【问题描述】:

我有一个名为 Collections 的字符串数组。

String[] Collections;

我的数据库表中保存了整数值。我想从名为 specific_collections 的数据库列中获取整数值。

并将其设置为整数数组 SpecificCollections。

所以,我想这样设置:

String[] Collections = 0;
Integer[] SpecificCollections = getColumnValuesFromSpecificCollectionsColumn(); 

在将它们设置为整数数组后,我想解析整数数组并将每个 int 值保存到我的字符串数组中,该数组形式如下:

Collections = new String[]{Collection.SpecificCollections.fromInt(SpecificCollections[i]).getString()};

Specific Collections 是来自 db 的整数数组。

编辑:这是我到目前为止所拥有的,但它只是用一个 int 填充列表?

ArrayList<Integer> regionList= new ArrayList<Integer>();
 Cursor cursorTwo = sqLiteDatabase.rawQuery("SELECT DISTINCT region FROM collection", null);
            if (cursorTwo != null && cursorTwo.getCount() != 0) {
                cursorTwo.moveToFirst();  
                while (!cursorTwo.isAfterLast()) {
                    regionList.add(cursorTwo.getInt(0));
                    cursorTwo.moveToNext();
                }
            }
            for (Integer inte : regionList){
                regions = new String[]{Collection.Regions.fromInt(inte).getString()};
            }

下面是遍历数组列表并在 fromInt() 方法中传递不同整数的正确方法吗?

【问题讨论】:

    标签: java android sql sqlite


    【解决方案1】:

    在 SQLiteDatabase.query() 方法中,将 selection 和 selectionArgs 参数设置为 null。例如看下面的代码:

    String[] projection = { COLUMN_NAME }
    Cursor cursor = mSQLiteDb.query(TABLE_NAME, projection, null, null, null, null, null);
    
    ArrayList<Integer> values = new ArrayList<Integer>();
    if (cursor != null && cursor.getCount() != 0) {
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
    
            values.add(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME)));
    
            cursor.moveToNext();
        }
    }
    

    【讨论】:

    • 你能告诉我如何使用光标查询吗?我尝试了一些解决方案,但没有一个有效。仅显示最后一个值。我尝试了这个解决方案但不起作用:stackoverflow.com/questions/19852821/…
    • 嗯,你能解释一下它是怎么不工作的吗?任何错误信息或什么?我更新了我的答案,请尝试代码。
    • 什么是setNumValue?在这种情况下 myObject 应该是什么?
    • 您可以忽略 myObject,我添加它是为了向您展示您可以将列的返回值存储在任何地方。我再次更新了代码并将 myObject 替换为整数数组列表
    • 不要忘记关闭光标。
    猜你喜欢
    • 2012-03-13
    • 2021-09-24
    • 2012-05-02
    • 2015-04-17
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多