简体   繁体   English

java.sql.SQLException:结果集开始之前

[英]java.sql.SQLException: Before start of result set

Here I have attached my code, it shows the error like: java.sql.SQLException: 在这里,我附加了代码,它显示了如下错误: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. 您可以在query1结果集循环内为query2使用新的ResultSet对象。

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. 但通常最好使用JDBC资源来遍历结果集1,收集返回的所有“城市”值,然后循环遍历“城市”结果,并调用query2以获得与状态2相关联的“状态”。 “城市”而非您所展示的方式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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