将数据库查询中的值返回到LinkedHashMap

时间:2017-04-28 19:21:46

标签: mysql jdbc linkedhashmap rowcount

我一直从这个LinkedHashMap中获取一个值,它是第一个[if(resultset.next())]或者是[while(resultset.next())],只有一个结果会回来,但我想要完整地图。如何返回符合我标准的表格中的所有行?任何帮助将不胜感激。

/** A method to list all previous statuses for a certain user given the userID */

public StringBuilder showStatusHistory(int userID) {

    try {

        Date date;
        String status;
        preparedStatement = createStatement("select statusDate,statusText from statusTable where userID = ?");
        preparedStatement.setInt(1,userID);
        resultSet = preparedStatement.executeQuery();

        StringBuilder allStatus = new StringBuilder("");
        statusesList = new LinkedHashMap<>();

        while (resultSet.next()){
            date = resultSet.getDate(1);
            status = resultSet.getString(2);
            statusesList.put(date,status);
        }

        Set<Date> statusTime = statusesList.keySet();
        for(Date k:statusTime){
            allStatus.append(k+" "+statusesList.get(k));
        }
        return allStatus;
    }
    catch (SQLException sqlE){
        sqlE.printStackTrace();
    }
    return null;

/ **使用辅助方法来最小化代码重复。它确实有效* /

private PreparedStatement createStatement(String query) {
    try {
        connection = DB_ConnectionConfiguration.getConnection();
        this.query = query;
        preparedStatement = connection.prepareStatement(query);
        return preparedStatement;
    } 
    catch (SQLException sqlE) {
        sqlE.printStackTrace();
        return null;
    }
}

1 个答案:

答案 0 :(得分:0)

以下示例代码中有几个建议......

public StringBuilder showStatusHistory(int userID) {
    // define at top and return "" if no results
    StringBuilder allStatus = new StringBuilder("");

    try {

        Date date;
        String status;
        // define local in the method
        PreparedStatement preparedStatement = createStatement("select statusDate,statusText from statusTable where userID = ?");
        preparedStatement.setInt(1, userID);
        // define local in the method
        ResultSet resultSet = preparedStatement.executeQuery();

        // append to the all Status here and skip the other loop
        // if you need a distinct list (like you had fro the Set) you could use a DISTINCT on the SQL statement.
        while (resultSet.next()) {
            date = resultSet.getDate(1);
            status = resultSet.getString(2);
            // append to the allStatus here 
            allStatus.append(date).append(" ").append(status);  // add a newline to the end? append(System.lineSeparator()) 
        }
    } catch (SQLException sqlE) {
        sqlE.printStackTrace();
        // do you want to throw this if something bad happened? 
    } finally {
       // close up your jdbc resources
    }

    // will contain "" if no records or concatenated statuses from the resultset
    return allStatus;
}