1

I try to get some data form database. The connection method works for sure, but I have a problem getting any data form DB:

    SQLConnect s = new SQLConnect();
    Connection c = s.getConnection();

    Statement st = c.createStatement();

    ResultSet rs = st.executeQuery("select * from produkty");
    System.out.println(rs.getString(2));

The problem is with the last line (when I comment it, no error appears). Error message:

Connected to database
Exception in thread "main" java.sql.SQLException: Before start of result set
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
    at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:841)
    at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5656)
    at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5576)
    at antmedic.Main.main(Main.java:85)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

Thanks for any help

Devel
  • 950
  • 9
  • 17
  • 29

4 Answers4

5

You need to call ResultSet#next() to shift the resultset cursor to the next row. Usually, when there's means of multiple rows, do this in a while loop.

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

Or when you expect zero or one row, use an if statement.

if (rs.next()) {
    System.out.println(rs.getString(2));
}

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • You're welcome. I would recommend to take a look at 2nd "see also" link. Your code namely suggests that you don't close the resources properly in `finally`. This is prone to resource leaking which may lead your application to crash after some time due to lack of resources. – BalusC Jan 03 '11 at 21:07
1

As you get the ResultSet object, the cursor points to the row before the first row, So after calling

while (rs.next()) {
//your code
}

the cursor points to the next row

i.e. the first row.

Ankit
  • 2,753
  • 1
  • 19
  • 26
0

Remember, whenever select query fires for retrieving the data from database into ResultSet, so the structure of ResultSet is

-> Zero Record Area

-> Database Record Area

-> No Record Area

that's why alwayz we must put next() with ResultSet object so it can move from Zero Record Area to Database Record Area.

0
     while(rs.next())
     {
        System.out.println(rs.getString(1));
        System.out.println(rs.getString(2));
     }

at the place of 1, 2, .... we can use the database columns name also. But technically always we use indexing like 1,2,3,.... its reason for any updation happening in future at our database like changes the column name so it can't be occur any problem for us because we haven't used the columns names.