mySQL - Get last added ID

83 Views Asked by At

Im a new programmer (just started on my programmer education).

Im trying to set my "tempVenueId" attribute with the last ID in my SQL DB: (in this case idvenue = 12)

Table name: venue

idvenue | name        | address
-------------------------------
 1      | Khar        | 5
 2      | SantaCruz   | 3
 3      | Sion        | 2
 4      | VT          | 1
 5      | newFort     | 3
 6      | Bandra      | 2
 7      | Worli       | 1
 8      | Sanpada     | 3
 9      | Joe         | 2
10      | Sally       | 1
11      | Elphiston   | 2
12      | Currey Road | 1

My code:

Private int tempVenueId;
SqlRowSet rs1 = jdbc.queryForRowSet("SELECT MAX(idvenue) FROM venue;");
while(rs1.next())tempVenueId = rs1.getInt(0);

/*I have also tried with "while(rs1.next())tempVenueId = rs1.getInt(1);"
*/

Still it does not work I get this when I run debug mode in intelliJ:

tempVenueId = 0 
2

There are 2 best solutions below

2
On

The index is from 1 rather than 0,so two ways to solve it:

while(rs1.next()){
   tempVenueId = rs1.getInt(1);
   break;
};

or

SqlRowSet rs1 = Jdbc.queryForRowSet("SELECT MAX(idvenue) as value FROM venue;");
while(rs1.next()){
  tempVenueId = rs1.getInt("value");
  break;
 }
3
On

Solved - This solution was alot easier.... (I think).


String sql = "SELECT LAST_INSERT_ID();"; 
SqlRowSet rs = Jdbc.queryForRowSet(sql);
rs.next();
Venue VN = new Venue(rs.getInt(1));
tempVenueId = VN;

  • Now i get the last AUTO INCREMENTET ID from DB