You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用SQLiteDatabase.rawQuery实现返回Integer列表的函数?

How to Return a List from SQLiteDatabase.rawQuery()

Hey there! The problem with your current code is that Cursor doesn't have a toInt() method—it's a result set holding all your query results, so you need to iterate through it to pull out each integer value one by one. Let's fix this up properly:

Corrected Implementation

public List<Integer> queryInt(String sql, String[] whereArgs) {
    List<Integer> resultList = new ArrayList<>();
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = null;

    try {
        // Execute the query and get the cursor
        cursor = db.rawQuery(sql, whereArgs);
        
        // Check if there are results to process
        if (cursor.moveToFirst()) {
            // Loop through every row in the cursor
            do {
                // Extract the integer from the first column (adjust index or use column name if needed)
                // For better robustness, use cursor.getColumnIndex("your_column_name") instead of 0
                int value = cursor.getInt(0);
                resultList.add(value);
            } while (cursor.moveToNext());
        }
    } finally {
        // Always close the cursor to avoid resource leaks
        if (cursor != null) {
            cursor.close();
        }
        // Note: If you obtained the db via SQLiteOpenHelper, you don't need to close it here
        // The helper manages the connection lifecycle. Only close if you opened it manually.
    }

    return resultList;
}

Key Details to Note:

  • Iterating the Cursor: We use moveToFirst() to check if the cursor has any data, then a do-while loop to iterate through every row. This ensures we don't skip the first row if results exist.
  • Extracting Values: The getInt() method requires a column index. If you know the exact name of the column you're querying (e.g., user_id), replace 0 with cursor.getColumnIndex("user_id")—this makes your code more resilient if the column order in your query ever changes.
  • Resource Management: The finally block guarantees the cursor gets closed even if an exception occurs, preventing memory leaks.

This implementation will safely return a list of integers from your SQLite query, or an empty list if there are no results.

内容的提问来源于stack exchange,提问作者Edouard de Schaetzen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:01:13