What is the difference between these two sql statements(JDBC)?

Viewed 47

I want to get last id in table. First I did this:

String selectId = "SELECT MAX(id) FROM book_store.cart" ;    
PreparedStatement ps = conn.prepareStatement(selectId);  
rs =  ps.executeQuery();
while(rs.next()){
    autoIncKey = rs.getInt("id");
}

Here I get error "column id not not found".

Then I changed the query to this, which is working:

String selectId = "SELECT id FROM book_store.cart ORDER BY id DESC LIMIT 1";

I am wondering why the first query is giving me an error and second does not if they are returning the same value?

1 Answers

The first query will return a row with a column name of MAX(id).

Not the most useful name for a column, so change the query to set an alias for that column like this

SELECT MAX(id) id FROM book_store.cart

And now the column will be called id and the rs.getInt("id") will work

Related