I have a JTextField named for Reservation ID on JFrame connected to MySQL database. Whenever I add a new passenger in the database, the JTextField should automatically generate a new Reservation ID for me in the JTextField based on an auto increment before I enter the passenger names and other details in the other textfields.
My code:
resId = new JTextField();
try{
rs = stt.executeQuery("select ReservID as last_id from passenger");
int lastid = rs.getInt("last_id");
lastid++;
resId.setText(String.valueOf(last_id));
}catch(Exception e){
JOptionPane.showMessageDialog(null, "cannot retrieve");
}
resId.setBounds(432, 178, 126, 22);
frame.getContentPane().add(resId);
resId.setColumns(10);
The last row of my column RevervID has value of 003. When I run the form, it should display me 004 in the Reservation ID textfield How do I achieve that ? Please help.. Thanks
The texfield in the image link below http://i.imgbox.com/wcf9KicU.png
First find out the maximum id using database query-> Select max(id) from mytable
Store the maximum id in a variable-> int max_id= max_id_from_database;
Increment max_id
by one-> max_id++;
add max_id value to your JTextField-> myJTextField.setText("" + max_id);
Edited: According to your code (just add max before ReservID and add rs.next() in a if condition and ReservID must be integer in your database).
resId = new JTextField();
try{
rs = stt.executeQuery("select max(ReservID) as last_id from passenger");
if(rs.next()){
int lastid = rs.getInt("last_id");
lastid++;
resId.setText(String.valueOf(last_id));
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, "cannot retrieve");
}