如何用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 ado-whileloop 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), replace0withcursor.getColumnIndex("user_id")—this makes your code more resilient if the column order in your query ever changes. - Resource Management: The
finallyblock 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
相关产品推荐
相关产品推荐

