如何在javafx textarea中显示计数查询的所有行?它只显示第一行而不是两行

0 javafx

我希望count和groupby(sqlite)sql查询的两行显示在文本区域中,但是它仅显示第一行。

当我将conn.close()语句放置在“ while”块之外时,它仅显示第二行,而忽略第一行

@FXML
private void viewResult(ActionEvent event)
{
    try
    {
        Connection conn = dbConnection.getConnection();
        Statement resultStmt = conn.createStatement();   
        ResultSet rs = resultStmt.executeQuery("select candidate, count(candidate) from voteResult group by candidate");
        while (rs.next()) {
            String news = rs.getString(1)+" "+rs.getString(2);
            this.result.setText(news);
            conn.close();
        }
    }
    catch (SQLException e)
    {
        System.err.println("Error " + e);
    }

}
Run Code Online (Sandbox Code Playgroud)

预期结果应如下所示:

JOSEPH THANKGOD 4
ORJI DANIEL 1
Run Code Online (Sandbox Code Playgroud)

Les*_*sum 6

每次调用setText(String value)前一个值将被覆盖。因此,您必须先构建结果字符串,然后再将其设置为内容TextArea。我不知道Connection其他组件如何精确地协同工作,但我想如果您Connection在第一个while循环周期中关闭自己的组件,ResultSet将无法再使用下一行。而且,第二次或第三次调用该close方法Connection不会导致任何事情发生,因为如果该Connection对象已经关闭,则它是无操作的。

@FXML
private void viewResult(ActionEvent event) {

    // Open resources with try-with-resources block
    try (Connection conn = dbConnection.getConnection();
        Statement resultStmt = conn.createStatement();
        ResultSet rs = resultStmt.executeQuery("select candidate, count(candidate) from voteResult group by candidate");){

        StringBuilder builder = new StringBuilder();
        while (rs.next()) {
            // Append each row
            builder.append(rs.getString(1)).append(" ").append(rs.getString(2)).append("\n");
        }

        // Remove last newline character
        if (builder.length() > 0) {
            builder.setLength(builder.length() - 1);
        }

        // Get complete string and set as TextArea content
        this.result.setText(builder.toString());

    // Resources will be closed automatically due to try-with-resources
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,您不应混用UI和数据库代码,而应使用try-with-resources块(请看此答案)。