java jdbc 异常中的结果集异常开始前

Before start of resultset exeception in java jdbc exception

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);
}

这里我在 setString 方法中遇到了一些问题。你能解释一下这个错误的原因吗?我试了很多方法这是jdbc

的问题吗

你可以想一个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()。或者,正如文档雄辩地指出的那样(我在相关句子中添加了一个 粗体强调 ):

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

长话短说 - 在执行查询后调用 rs.next() 将其推进到第一行(也是唯一一行):

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
}