优雅打印查询的结果

时间:2015-07-30 19:12:01

标签: java database

我正在编写一个应用程序,用户可以在其中连接到MySQL数据库并执行一些查询。

我将结果放在ResultSet中,但我找不到一种优雅的方式将结果打印到textArea。

java是否有专门用于打印查询结果的类?

1 个答案:

答案 0 :(得分:0)

将表映射到类和结果查询。例如,您在数据库中有一个表Users,您希望获取所有这些用户并在JTextArea上打印它们。

public class User {

    private Long id;
    private String firstName;
    private String lastName;
    private String email;

    // constructors, getters and setters

    @Override
    public String toString() {
        return "ID: " + id +
        "\nFirst name: " + firstName +
        "\nLast name: " + lastName +
        "\nEmail: " + email;
    }
}

在你的DAO中:

public List<User> getAllUsers() {
    List<User> users = new ArrayList<>();

    try(Connection con = ConnectionHelper.get();
        Statement st = con.createStatement()) {
            String query = "SELECT * FROM User";
            ResultSet rs = st.executeQuery(query);

            // check if resultset is empty
            if(!rs.isBerforeFirst()) {
                throw new RuntimeException("Not users found");
            }
            // iterate over result set and wrap
            // data in User bean
            while(rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setFirstName(rs.getString("firstname"));
                user.setLastname(rs.getString("lastname"));
                user.setEmail(rs.getString("email"));
                users.add(user);
            }
    } catch(SQLException e) {
        throw new RuntimeException("Error when fetch users", e);
    }

    return users;
}

在您的控制器或视图中:

try {
    UserDao dao = new UserDao();
    List<User> allUsers = dao.getAllUsers();
    for(User user : allUsers) {
        textArea.append(user); // implicit call toString
    }

} catch(RuntimeException e) {
    // log 'Not users found' or 'Error when fetch users'
    Logger.getLogger(getClass().getName())
        .log(Level.SEVERE. e.getMessage());
    e.printStackTrace();
}