这里我附上了我的代码,它显示的错误如下: java.sql.SQLException:
在结果开始之前,我在这里做错了什么:
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);
}
}
答案 0 :(得分:1)
您可以在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");
但一般来说,更好地利用JDBC资源来遍历结果集1,收集返回的所有“city”值,然后遍历“city”结果调用query2来获取“状态”与“城市”相关联,而不是你们表现出来的方式。
答案 1 :(得分:0)
您的代码中不需要第二个结果集。 State 和 City 都可以在同一个结果集中找到。您可以使用以下代码:
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);
}
}