当前位置:首页 > 数据库 > SQlite

java-SQLite数据库查询仅返回一行

下面是我用来获取存储在SQLite表中的所有结果的代码.我遇到的问题是,当我知道数据库中有21行时,它仅返回一行.

public HashMap<String, String> fetchResults(String TABLE_NAME, String sql) {
    HashMap<String, String> table = new HashMap<String, String>();
    if(sql == null)
        sql = "";
    String selectQuery = "SELECT * FROM " + TABLE_NAME + " " + sql;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    String[] columns = null;
    switch(TABLE_NAME ){
    case "projects":
        columns = dbTables.projectsColumns;
        break;
    }



    // Move to first row
    cursor.moveToFirst();
    if (cursor.getCount() > 0) {

        int n=1;
        for(int i=0; i<columns.length; i++){
            table.put(columns[i], cursor.getString(n));
            n++;
        }

    }
    //move to the next row 
    cursor.moveToNext();

    cursor.close();
    db.close();
    // return user
    Log.d(TAG, "Fetching " + TABLE_NAME + " from Sqlite: " + table.toString());

    return table;
}

db调用在一个片段中进行,如下所示.

HashMap<String, String> projects = db.fetchResults(dbTables.TABLE_PROJECTS, null);


    for (String key : projects.keySet()) {

        if(key == "projectname"){
            System.out.println("Key: " + key + ", Value: " + projects.get(key));
            menuList.add(projects.get(key));
        }
    }

解决方法:

您只在那里检索一行:

// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
    int n=1;
    for(int i=0; i<columns.length; i++){
        table.put(columns[i], cursor.getString(n));
        n++;
    }
}

您必须迭代游标才能获得所有结果:

// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
    while(cursor.moveToNext()) {
        for (int i = 0; i < columns.length; i++) {
            table.put(columns[i], cursor.getString(i));
        }
    }
}

但是您的表将列出每一行的所有列值.如果要使用带有行条目的表,请定义一个用于存储列值的类.


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!