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
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 returnsfalse
when there are no more rows in theResultSet
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
}