从数据库返回有序键值对 - Java

时间:2017-12-28 12:42:07

标签: java treemap

我正在尝试从derby数据库中的键值对创建一个联盟表 - 数据库中的行只有两列,TeamName&目标

我需要将这些内容添加到我的GUI类中,以便我可以设置键和键。在联赛表中作为JLabels的值。从总目标的角度排列自上而下降。

从我读过的LinkedHashMap& TreeSet应该都能帮助我。

我到目前为止的代码:

public TreeMap viewTeams(){
    TreeMap teamData = new TreeMap();
    String viewTeams = "SELECT * FROM HUI.TEAM";
    connectToDatabase(dbName);
    try {
        stmt = dbConnection.createStatement();
        rs = stmt.executeQuery(viewTeams);
    } catch (SQLException error) {
        System.err.println("Error querying database for teams: " + error.toString());
    } 
    try {
        while (rs.next()){
            teamData.put((rs.getString("TEAMNAME")), (rs.getInt("GOALSSCORED")));
        }
    } catch (SQLException error) {
        System.err.println("Error adding players to HasMap: " + error.toString());
    }
    return teamData;
}

在TeamDB类

public void updateLeagueTable(){
    TeamDB tdb = new TeamDB("FootManDatabase");
    TreeMap teamData = tdb.viewTeams(); // Do I need this new TreeMap?
    // How do I Iterate through the pairs in descending order?
}

在GUI类

1 个答案:

答案 0 :(得分:0)

我只是让SQL数据库进行排序,因为它可以做得很好。

此外,您不能使用TreeMap<String, Integer>,因为它会按团队名称而不是目标进行迭代。并且你不能使用TreeMap<Integer, String>因为它不允许重复,所以你将无法让两支球队得分相同。相反,我会使用一个列表。类似下面的内容(但请记住正确关闭资源,为清晰起见,我已经遗漏了这些资源)。

class TeamScore {
    private final String name;
    private final int numGoals;
    public TeamScore(String name, int numGoals) {
        this.name = name;
        this.numGoals = numGoals;
    }
    // getters...
}


public List<TeamScore> viewTeams() throws SQLException {
    List<TeamScore> teamData = new ArrayList<>();
    String viewTeams = "SELECT * FROM HUI.TEAM ORDER BY GOALSSCORED DESC";
    connectToDatabase(dbName);
    stmt = dbConnection.createStatement();
    rs = stmt.executeQuery(viewTeams);
    while (rs.next()) {
        teamData.add(new TeamScore(rs.getString("TEAMNAME"), rs.getInt("GOALSSCORED"));
    }
    return teamData;
}