Diana
Diana

Reputation: 315

SQL in Java. Cannot receive the result set

I hope that you can correct me if my syntax is wrong. I could check on Google only if the SELECT...WHERE clause is correct.

I want to retrieve the student_id for using it in another query, but seems that all I get from this is a "0".

in java file:

rst = stmt.executeQuery("SELECT student_id FROM students WHERE name= 'to_delete'");
sid = rst.getInt("student_id");

to_delete is a String which this java file receives as a parameter to the method which must return student_id. It really contains the correct string(I checked it).

Table "students" contains the fileds: student_id, name, year. I need to have returned the student_id for the name "to_delete".

I have no errors/exceptions, just that when I display the result, I see id: 0 no matter what name I type. Maybe rst.getString("column_name") is correct only for executeUpdate(...)?

Thank you in advance!

Upvotes: 2

Views: 174

Answers (2)

Nathan Hughes
Nathan Hughes

Reputation: 96395

Call next() on the resultset before you try to get anything out of it. You iterate through the ResultSet by calling the next method every time you want to read a row. When next returns false you're done.

Here's the API documentation for the next method:

boolean next() throws SQLException

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. If the result set type is TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver implementation will return false or throw an SQLException on a subsequent call to next.

If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.

Returns: true if the new current row is valid; false if there are no more rows Throws: SQLException - if a database access error occurs or this method is called on a closed result set

Upvotes: 3

TechGuy
TechGuy

Reputation: 4570

Yes.the problem is you should call next() before you try to get from it.Otherwise you did not get any error but No results.

Upvotes: 0

Related Questions