我这里有一段Java代码,它应该从数据库查询中检索结果,并且ResultSet应该迭代这些值,以便为ResultSet的每个条目检索某些API数据。 但是,问题是我只能检索ResultSet的第一个条目的API数据。
此代码完全按预期工作,并返回所有数据库条目。
try {
ResultSet rs;
rs = stat.executeQuery("select * from schedule");
while (rs.next()) {
model.addRow(new Object[]{rs.getString("SHOW"), rs.getString("SEASON")});
}
} catch (Exception e) {
console.append(e.getMessage() + '\n');
}
但是,此代码仅返回第一个条目。
try {
ResultSet rs = stat.executeQuery("select * from schedule");
while (rs.next()) {
String show = rs.getString("SHOW");
String season = rs.getString("SEASON");
String api_url = "<API_URL>/" + show + "/" + season;
URL url = new URL(api_url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
if (responseCode == 200) {
conn_stat.setText("Connection Status : OK");
} else {
conn_stat.setText("Connection Status : ERR");
}
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String s = response.toString();
JsonArray json = JsonArray.readFrom(s);
for (int i = 0; i < json.size(); i++) {
JsonObject show_json = json.get(i).asObject();
int episode = show_json.get("episode").asInt();
String date = show_json.get("first_aired_iso").asString();
String title = show_json.get("title").asString();
String date_formatted = date.substring(0, date.indexOf("T"));
SimpleDateFormat original = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat target = new SimpleDateFormat("dd-MMM-yyyy");
Date unformatteddate = original.parse(date_formatted);
String dateStart = target.format(unformatteddate);
Date curr_date = new Date();
String dateStop = target.format(curr_date);
Date d1 = null;
Date d2 = null;
d1 = target.parse(dateStart);
d2 = target.parse(dateStop);
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000);
if (diffDays < 0) {
alert_model.addRow(new Object[]{show + " - " + episode, title, dateStart});
}
}
}
} catch (Exception e) {
console.append(e.getMessage() + '\n');
}
答案 0 :(得分:3)
尝试分解你的逻辑。这是您从数据库创建所有节目/季节的列表的方法。
try {
ResultSet rs = stat.executeQuery("select * from schedule");
List<String[]> list = new ArrayList<>();
while (rs.next()) {
String show = rs.getString("SHOW");
String season = rs.getString("SEASON");
list.add(new String[]{show, season});
}
}
catch (Exception e) {
e.printStackTrace();
}
在结果集(可能还有连接)关闭之后,您应该使用此列表构造ULR并查询外部服务。