简体   繁体   中英

java exception : Before start of result set

I have two tables the first one is for "course" and the other is for "exam":

在此处输入图像描述在此处输入图像描述

I want select exams which are matched to the code, of course, get by entering its name (nomCours)

here is my code:

try {
    String select1 = "select code from cours where nomCours=?";
    st2 = con.prepareStatement(select1);
    st2.setString(1, nom);
    rs2 = st2.executeQuery();
    System.out.println(rs2.getInt("code"));

    String select = "SELECT matricule FROM examen where code=?";
    st = con.prepareStatement(select);
    st.setInt(1, rs2.getInt("code"));
    rs = st.executeQuery();
    while (rs.next()) {
        System.out.print(rs.getInt("matricule")+"  ");
    }
} catch (SQLException ex) {
    System.err.print(ex);
}

this doesn't work, and it gives me this error:

java.sql.SQLException: Before start of result set

When you execute a query, you get a ResultSet that points to the so-called before-first row. You need to advance it in order to get the first row of the result:

rs2 = st2.executeQuery();
if (rs2.next()) {
    System.out.println(rs2.getInt("code"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM