Home > Software engineering >  Getting SQL Exception when trying to get the last auto-incremented value
Getting SQL Exception when trying to get the last auto-incremented value

Time:05-19

I've been trying everything, nothing is working, I'm new to mysql and databases and I want to get the last auto-incremented id (primary key) (user_id) from a table, from java. So this: SELECT MAX(user_id) FROM database_user; works fine in mysql, I got that, but why can't I get the same thing from java??

PreparedStatement st = connection.prepareStatement("SELECT MAX(user_id) from database_user");
st.executeUpdate();
ResultSet rs = st.executeQuery();
int uid = rs.getInt(1);
System.out.println(uid);

This gives me java.sql.SQLException: (conn=213) the given SQL statement produces an unexpected ResultSet object

This isn't the only thing I tried, it's just the last one so far. If anyone could just shed some light I would greatly appreaciate it.

CodePudding user response:

You are missing rs.next(); between executing the query and fetching from the result set. This is needed, to move the result set to the first row.

You also shouldn't have st.executeUpdate(). Just executing once is enough.

  • Related