I am having table stored in database i am trying to retrieve all data in it Why i get this error when i tried to retrieve all records in my database? Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 185 at warsh01.selectStmt01.getObjectIDsFromDB(selectStmt01.java:83)
public static int[] getObjectIDsFromDB (String Dbnum) throws SQLException{
String selectSQL = "SELECT ID FROM " + Dbnum +.tabName ";
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(selectSQL);
ResultSet rs = preparedStatement.executeQuery();
rs.last();
int[] rsIds=new int[rs.getRow()];
rs.beforeFirst();
int counter = 1;
while (rs.next()) {
rsIds[counter]=rs.getInt(1);
counter++; // the error is pointing in this line
}
return rsIds;
}
in the main method when i tried to run it i got the above exception
int [] IdsArray ;
pathIdsArray = getObjectIDsFromDB ("za");
List<ObjClass> objItm=new ArrayList<>();
for (int i = 1; i < IdsArray.length; i++) {
Item1 = new ObjClass ();
objectItem1.color=Color.blue;
objectItem1.LoadFromDB("za", IdsArray[i]);
objItm.add(Item1);
}
I think that you should simply initialise counter
to 0
instead of 1
:)
Let's say that your ResultSet
has 4 rows . rsIds
then is an Array
of four int
, from rsIds[0]
to rsIds[3]
.
By initialising counter
to 1
and entering 4 times in the while (rs.next())
loop, you:
rsIds[0]
value rsIds[4]
(which you can't) in the last iteration. Hope it helps!
ResultSets have indices starting at 1. But Java arrays have indices starting at 0. You're iterating through the result set with a counter starting at 1, and at each iteration, you initialize rsIds[counter]
. You should initialize rsIds[counter - 1]
instead (or start the counter at 0).
Note that using a List instead of an array would be much easier:
List<Integer> result = new ArrayList<Integer>();
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
result.add(rs.getInt(1));
}
In Java arrays are zero indexed, ie the first element has the index 0
. You are using the counter
variable to access the array's positions, but initialize it with 1
.
int counter = 1;
while (rs.next()) {
rsIds[counter]=rs.getInt(1);
counter++;
}
Let the row count be eg 5, then you have an array with five "positions" 0,1,2,3,4 . But inside the while loop you are accessing 1,2,3,4, 5 - resulting in an violation of array boundaries.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.