try {
    String sql ="select * from staff where id=? ";

    pst=conn.prepareStatement(sql);
    pst.setString(1,txt_search.getText());
    rs=pst.executeQuery();

    String add1 =rs.getString("id");
    txt_empid.setText(add1);

    String add2 =rs.getString("Name");
    txt_firstname.setText(add2);

    String add5 =rs.getString("Salary");
    txt_salary.setText(add5);

}catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
}

here I have some problem in setString method. Can you please explain the reason for this error. I try lot of ways is this a problem of jdbc

upvote
  flag
Can you add the exact error message you're getting? – Jacob Wood
upvote
  flag
java.sql.SQLException Before start of result set – Dhananjana

1 Answers 11

up vote 1 down vote accepted

You can think of a ResultSet as an iterator to the returned data. To access any row in the returned data, including the first, you need to advance the cursor to it by calling next(). Or, as the documentation eloquently puts it (I added an emphasize in bold to the relevant sentence):

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

To make a long story short - call rs.next() after you execute the query to advance it to the first (and only) row:

rs = pst.executeQuery();

if (rs.next()) {
    String add1 = rs.getString("id");
    txt_empid.setText(add1);

    String add2 = rs.getString("Name");
    txt_firstname.setText(add2);

    String add5 = rs.getString("Salary");
    txt_salary.setText(add5);
} else {
    // The query returned no rows - i.e., the given ID doesn't exist in the table.
    // Some error handling is required here
}
upvote
  flag
Thank you very much Mureinik It work so efficiently – Dhananjana

Not the answer you're looking for? Browse other questions tagged or ask your own question.