Retrieve an aggregated SQL value from a ResultSet in Java -


i've been stuck problem several hours: there 3 tables, 1 of them connects others through place number , tray id. find out how many samples on specific tray aggregated places tray id, works in pure sql code.

my java code:

 ps = connection.preparestatement("select trayid, count(placeno) occupied " +                                                 "from place " +                                                 "group trayid " +                                                 "having trayid = ?");          ps.setint(1, trayid);          rs = ps.executequery();          if (!rs.isbeforefirst()) { throw new coolingsystemexception(); }          else {              spaceoccupied = rs.getint("occupied"); 

and last line program crashes. have tried getint(1) instead of name nothing works. , if result set empty crash @

if (!rs.isbeforefirst()) { throw new coolingsystemexception(); } 

what know sure there value

image: dbeaver using same trayid

i sure spot because logged @ each imaginable point before , after each line.

does has idea how solve it? tried every datatype in get...() function :(

your problem after check whether there data in result set, you're not moving cursor forward rs.next() before calling rs.getint(). seems you're ever expecting result set contain 1 row, can following instead:

ps = connection.preparestatement("select trayid, count(placeno) occupied " +                                             "from place " +                                             "group trayid " +                                             "having trayid = ?");  ps.setint(1, trayid); rs = ps.executequery();  if (rs.next()) {     spaceoccupied = rs.getint("occupied"); } else {     throw new coolingsystemexception(); } 

the first invocation of rs.next() return falsey if query didn't return data.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -