Java 循环遍历数据库结果集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19876451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:59:02  来源:igfitidea点击:

Looping through database ResultSet

javasqljdbch2

提问by Kanishka Ganguly

I have a snippet of Java code here which is supposed to retrieve results from a database query and the ResultSet is supposed to iterate through the values in order to retrieve certain API data for each entry of the ResultSet. However, the problem is that I can retrieve API data for only the first entry of my ResultSet.

我在这里有一段 Java 代码,它应该从数据库查询中检索结果,ResultSet 应该遍历这些值,以便为 ResultSet 的每个条目检索某些 API 数据。但是,问题是我只能检索 ResultSet 的第一个条目的 API 数据。

This code works exactly as expected and returns all my database entries.

此代码完全按预期工作并返回我的所有数据库条目。

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

However, this code returns only the first entry.

但是,此代码仅返回第一个条目。

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

采纳答案by Andreas Wederbrand

Try to split up your logic. This is how you create a list of all shows/seasons from the database.

尝试拆分您的逻辑。这就是您从数据库中创建所有节目/季节列表的方式。

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

You should then construct ULRs and query the external service using this list, after the resultset (and possibly the connection) is closed.

然后,在结果集(可能还有连接)关闭后,您应该构造 ULR 并使用此列表查询外部服务。