I am manually incrementing my ID number in my database as I can't get it to work automatically. It is for a project and doesn't matter if it doesn't work automatically - I can try and solve that later.
I am creating a method which checks for the lowest free ID number in a resultSet. The lowest will be set as an integer called availableId which users will be given upon registration.
This is what I have got so far from reading:
http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html http://wiki.netbeans.org/GetStartedwithJavaDB
As an example, these are my IDs in my database:
/,2,/,4,5,6,/,8,9
1, 3 and 7 are missing as those users deleted their accounts. I want to fill number 1 before I fill any others and then the next user will register as number 3 for example.
public int getAvailableId() {
int availableId = 1;
try {
String stmt = "select PID from APP.PERSON";
PreparedStatement ps = Main.getPreparedStatement(stmt);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int n = rs.getInt(1);
int n2 = rs.next().getInt(1);
if (!(n == 1)) {
return availableId;
} else if (!(n2-- == n)) {
availableId = n++;
}
}
rs.close();
ps.close();
} catch (Exception e) {
System.out.println(e);
}
return availableId;
}
Two problems here:
rs.next()
returns a boolean, but I want n2 to hold the value of the integer in the next row - I can't find a method that does this from here - http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html- I can't figure out how to loop through everything to find the lowest possible free id number.
Please excuse the rubbish code! I am learning a lot as I go along and I understand this is bad practice for one and two the code isn't great.
How can I go about doing this?