0

I'm new to java, i tried to print all data in the table

    Statement stmt=connection.createStatement();
    String sql ="INSERT INTO contacts(name,email)VALUES('ABC','ABC@yahoo.com')";
    stmt.execute(sql);
    ResultSet rs=stmt.executeQuery("SELECT*FROM contacts");
    System.out.println(rs.getString("name"));

and got

Exception in thread "main" org.h2.jdbc.JdbcSQLException: No data is available [2000-173]
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71

1 Answers1

4

You need to call rs.next() before calling rs.getString("...").

...
ResultSet rs=stmt.executeQuery("SELECT * FROM contacts");

while(rs.next()) {
    System.out.println(rs.getString("name"));
}

If you're expecting only 1 row, then you can also do:

...
ResultSet rs=stmt.executeQuery("SELECT * FROM contacts");

if(rs.next()) {
    System.out.println(rs.getString("name"));
}
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
  • thanks for helping, it worked but why while didn't work ? –  Mar 15 '17 at 06:06
  • @user5520049 You don't show any `while` loops in your question... – Mark Rotteveel Mar 15 '17 at 08:24
  • sorry i forgot to write it , i used while and got contacts id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :id is :Exception in thread "main" org.h2.jdbc.JdbcSQLException: No data is available [2000-173] but when i used if it worked –  Mar 15 '17 at 20:24