Java实现将ResultSet转为二维ArrayList的getData方法报错求助
Hey there! Let's break down the issues in your code step by step and fix them properly.
First, the initial error explanation
The error error: array required, but ArrayList<ArrayList<String>> found happens because you're trying to access an ArrayList like a regular Java array with ary[row][i-1]. Unlike arrays, ArrayLists don't support bracket-style indexing for assignment—you need to use their built-in methods like add() and get() to manipulate elements. On top of that, your initial code had a hidden bug: the ary list was empty, so even if you tried using get(row), it would throw an IndexOutOfBoundsException since no row elements had been added yet.
Fixing the core logic + handling exceptions
Your edited code fixed the indexing issue, but it had another problem: you were adding the same row to the main list numFields times (since ary.add(columnsList) was inside the inner for loop). Here's the fully corrected version that also addresses the exception requirement from jGrasp:
public ArrayList<ArrayList<String>> getData(String sqlString, int numFields) throws SQLException { // Use try-with-resources to auto-close Statement and ResultSet (critical for resource management) try (Statement stmnt = this.conn.createStatement(); ResultSet rs = stmnt.executeQuery(sqlString)) { ArrayList<ArrayList<String>> ary = new ArrayList<>(); while (rs.next()) { // Iterate over each row in the result set ArrayList<String> columnsList = new ArrayList<>(); for (int i = 1; i <= numFields; i++) { // Iterate over each field in the current row columnsList.add(rs.getString(i)); } // Add the completed row to the main list (moved outside the inner loop!) ary.add(columnsList); } return ary; } }
Key improvements made:
- Replaced array-style indexing with proper
ArrayList.add()calls to build rows and the main list - Moved
ary.add(columnsList)outside the inner for loop to avoid duplicate rows - Added
throws SQLExceptionto the method signature (JDBC operations throw checked exceptions, so you must either declare them or catch them) - Used try-with-resources syntax to automatically close
StatementandResultSet—this prevents resource leaks, which is a best practice for JDBC code
If you prefer catching exceptions instead of propagating them
If you don't want to pass the exception up to the caller, you can wrap the code in a try/catch block:
public ArrayList<ArrayList<String>> getData(String sqlString, int numFields) { ArrayList<ArrayList<String>> ary = new ArrayList<>(); try (Statement stmnt = this.conn.createStatement(); ResultSet rs = stmnt.executeQuery(sqlString)) { while (rs.next()) { ArrayList<String> columnsList = new ArrayList<>(); for (int i = 1; i <= numFields; i++) { columnsList.add(rs.getString(i)); } ary.add(columnsList); } } catch (SQLException e) { // Handle the exception here—log it, show an error message, or add custom logic e.printStackTrace(); } return ary; }
内容的提问来源于stack exchange,提问作者Ryan

