0

I have a table with this columns (id,name,isbn,borrowedStatus(varchar),Date) and some rows in my table.

Now i want to get borrowedStatus value for a specific id,then i need to recognize that String (yes, or no). Here is my code:

public void booksTableBorrowChanged(int rowInModel) {
    Object bookId = this.getValueAt(rowInModel, 0);
    Connection con;
    PreparedStatement ps1;
    String query1 = "select borrowedStatus from books where id=" + bookId;
    ResultSet rs = null;
    try {
        con = DriverManager.getConnection(...);
        ps1 = con.prepareStatement(query1);
        rs = ps1.executeQuery();
        if (String.valueOf(rs.getString("BorrowedStatus")).equalsIgnoreCase("No")) {  // then do Borrow Action
            System.out.println("Old statuse : No");

           // then do other stuff

        }

    } catch (SQLException sqle) {
        sqle.printStackTrace();
    }

}

But this code has this exception when executed:

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)
...

How can i solve this problem?

  • Could it be your driver doesn't support pre-compilation of statements? – Mena Jul 07 '14 at 09:36
  • @Mena I can't understand your mean correctly, I use `mysql` database with `JDBC` driver, Other par of my program work correctly with database . –  Jul 07 '14 at 09:39
  • See Ray's answer - I had completely missed that. – Mena Jul 07 '14 at 09:42
  • Don't build SQL queries by concatenating strings. That's how you get SQL injections. You're *maybe* safe in this case, but better to *never* do it. http://en.wikipedia.org/wiki/SQL_injection – Christoffer Hammarström Jul 07 '14 at 09:50
  • @ChristofferHammarström Nice point, But how will be the form of SQL queries without string concatenating? By using of `?` ? –  Jul 07 '14 at 11:54
  • [Here's a question showing how to *not* do it, with responses showing how.](http://stackoverflow.com/questions/1812891/java-escape-string-to-prevent-sql-injection) – Christoffer Hammarström Jul 07 '14 at 11:58

1 Answers1

1

From ResultSet's Javadoc:

ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

Notice the sentence starting with "Initially": You first have to call next before being able to access any data.

Ray
  • 3,084
  • 2
  • 19
  • 27