简体   繁体   中英

java.sql.SQLException: Before start of result set

Here I have attached my code, it shows the error like: java.sql.SQLException:

Before start of result set what I am doing wrong here:

String qry = "SELECT * From register ";



stmt = (PreparedStatement) conn.prepareStatement(qry);
rs =  stmt.executeQuery();
while (rs.next()) {
    String area = rs.getString("city");
    if(city.equals(area)){
        System.out.println("!!!!!!It matched: " + city);
        String qry2="select state from register where city='"+city+"'";
        System.out.println(qry2);
        stmt = (PreparedStatement) conn.prepareStatement(qry2);
        rs =  stmt.executeQuery();
        String state=rs.getString("state");
        System.out.println("state: " + state);
        break;
    } else {
        //System.out.println("No match with: " + area);
    }
}

You can use a new ResultSet object for query2 inside the query1 result set loop.

String qry2="select state from register where city='"+city+"'";
System.out.println(qry2);
stmt = (PreparedStatement) conn.prepareStatement(qry2);
ResultSet rs2 =  stmt.executeQuery();
String state=rs2.getString("state");

But generally it would be a better use of JDBC resources to iterate all the way through result set 1, collecting all the "city" values returned, and then loop through the "city" results calling query2 to get the "states" associated with the "cities" instead of they way you've showed.

Second resultset is not required in your code. State and City both can be found in same resultset. You can use the following code:

String qry = "select * from register";
PreparedStatement stmt = (PreparedStatement) conn.prepareStatement(qry);
             rs =  stmt.executeQuery();
             while (rs.next()) {
                 String area = rs.getString("city");
                 if(city.equals(area)){
                    System.out.println("!!!!!!It matched: " + city);
                    String state=rs.getString("state");
                    System.out.println("state: " + state);
                    break;
                 } else {
                    //System.out.println("No match with: " + area);
                 }
           }

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