Your code is slightly wrong. This needs to be changed:
rs.next().getInt(1);
To just:
rs.getInt("PID");
rs.next()
does two things. Returns true if there is a next row, and then moves the resultset cursor to point to the next row.
When there is no next row it will return false and hence break out the loop.
When you call getInt
it will try to retrieve the int from the current row. As you can see the rs.next()
in the loop condition will move it to the next row each time.
Also in this case you will need to declare
int n
outside of the loop.
and then assign n = n2
at the end of each loop iteration.
Something like this:
int n = 0;
while (rs.next()) {
int n2 = rs.getInt(1);
if (!(n == 1)) {
return availableId;
} else if (!(n2-- == n)) {
availableId = n++;
}
n = n2;
}
You may need to play around with it to get it doing exactly what you want.
My final comment, dont bother trying to get the lowest possible free id number, just get the highest number from the database usign a SQL MAX() or something and then add 1.