Reputation: 21
hello evryone am working a student management system and for saving students information in mysql database am using an auto-increment but i want make all StudentID to start with "ST" followed by the "Currentyear" then a number that will be incremented automaticly and be didplayed in a jTextField i have designed and named "jTextFieldstudentid" the probeme is when i run the file, the output is not corresponding to what i need, in the students Table on mysql dB the last ID = "ST2020001" but in the jTextField am getting "ST20200012020002" instead of "ST2020002" please help, i dont know if there is something wrong with my code.
private void StudentAutoID()
{
try {
String sql="SELECT StudentID FROM students ORDER BY StudentID DESC LIMIT 1";
PreparedStatement pst=con.prepareStatement(sql);
ResultSet rs=pst.executeQuery();
if(rs.next())
{
Date d=new Date();
int year=d.getYear();
int currentYear = year+1900;
String rnno=rs.getString("StudentID");
int co=rnno.length();
String txt= rnno.substring(0, 2);
String num=rnno.substring(2, co);
int n=Integer.parseInt(num);
n++;
String snum=Integer.toString(n);
String ftxt=txt+currentYear+snum;
jTextFieldstudentid.setText(ftxt);
}
else
{
jTextFieldstudentid.setText("ST2020000");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, e);
}
}```
Upvotes: 1
Views: 598
Reputation: 737
The problem is in this line:
String num=rnno.substring(2, co);
Your substring includes the year as well.
If you change it to:
String num=rnno.substring(6, co);
it will work as expected.
However, I would reconsider the model. It might be better to keep atomic fields for a year and a numerical id; and based on those fields to calculate the student id in the java code without the invocations of the substring method.
Upvotes: 2