简体   繁体   English

如何将列动态添加到jTable并使用数据库中的值填充它

[英]How to dynamically add a column to a jTable and populate it with values from a database

I am trying to add values from a query to a jTable column that I have created on the fly. 我试图将查询中的值添加到即时创建的jTable列中。 The code that I have written below on populates the column with a single value. 我在下面编写的代码用单个值填充该列。

    TableColumn c = new TableColumn();
   c.setHeaderValue("Test");
   ((DefaultTableModel) jTable2.getModel()).addColumn(c);
    String sql = "select COUNT(COURSEBOOKED) as count from APP.BOOKCOURSE where COURSEBOOKED =?";
    try(Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
            PreparedStatement pst = con.prepareStatement(sql);){
                 for(int row = 0; row < jTable2.getRowCount(); row++){
                        DefaultTableModel model = (DefaultTableModel)jTable2.getModel();
                        String selected = model.getValueAt(row, 1).toString();
                        pst.setString(1, selected);
                        try(ResultSet rs = pst.executeQuery();){
                            for(int col = 0; col<jTable2.getRowCount(); col++){
                                     if(rs.next()){
                                      Sum = rs.getString("count");
                              jTable2.setValueAt(Sum, col, 12);   
                              System.out.println(Sum);
                                    }
                                 }
                        }
                    }
                }

    catch(SQLException e){
        JOptionPane.showMessageDialog(this, e);
    }

The output that I require added to the table should be: 我需要添加到表中的输出应为:

0 0 0 2 0 1 0 0 0 0 2 0 1 0

But I am actually getting: 但是我实际上正在得到:

0 0

Which means that the value being added to the column is the first value of the result query.But the results that i get from printing to the console are 这意味着添加到该列的值是结果查询的第一个值。但是我从打印到控制台得到的结果是

0 0 0 2 0 1 0 0 0 0 2 0 1 0

How can I solve this dilemma that I am in? 如何解决我所处的困境?

You are adding the last element only, because you iterate through the while loop and get the last element and set that value. 您仅添加最后一个元素,因为您遍历while循环并获取最后一个元素并设置该值。

for(int col = 0; col<jTable2.getRowCount(); col++){
   if(rs.next())
      jTable2.setValueAt(rs.getString("count"), col, 12);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM