4

How can I solve this error and what is the problem?

Here is my code:

     String sql = "select min(pressure),max(pressure),avg(pressure) from userinfo";
    pst = conn.prepareStatement(sql);
    rs = pst.executeQuery();
    String add1 = rs.getString("min(pressure)");
    min_pressure.setText(add1);
    String add2 = rs.getString("max(pressure)");
    max_pressure.setText(add2);
    String add3 = rs.getString("avg(pressure)");
    avg_pressure.setText(add3);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }

This results in the exception:

java. sql. SQLException: Before Start Of ResultSet

Raihan Uddin
  • 116
  • 1
  • 9
  • 1
    You should also use the [try-with-resources statement](http://stackoverflow.com/questions/8066501/how-should-i-use-try-with-resources-with-jdbc) for managing JDBC resources efficiently and properly. – Mick Mnemonic Mar 27 '16 at 18:30
  • 1
    you might want to go through the [JDBC tutorial](http://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html) –  Mar 27 '16 at 18:39

2 Answers2

3

The ResultSet javadoc says (in part) initially the cursor is positioned before the first row. Advance the resultset cursor to the first row by calling next() like

rs = pst.executeQuery();
rs.next(); // <-- or if (rs.next()) {
String add1 = rs.getString("min(pressure)");
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0
rs = pst.executeQuery();
if (rs.next()) {
    String add1 = rs.getStr
}
Floern
  • 33,559
  • 24
  • 104
  • 119