Select SQL 查询只返回 tableModel 中数组的一个值

Select SQL query returning only one value of array in the tableModel

我正在尝试从数据库中的特定 categories table 中获取具有相似类别名称的商品的行,并且对于每一行,我都做了第二个 SQL 查询 orders table 过去一周的订单数量总和。我想将结果添加到 table 模型,但只添加了一行。

private void analyticsTableQuery(String Category) {
    this.categorySelected = Category;
    categoryTitle.setText(Category);
   int ordered;
    int initial;
    String query2 = "SELECT * FROM stock INNER JOIN category ON stock.Category_id=category.id where category.Category_Name='"+Category+"'";
    try {
            con = DriverManager.getConnection("jdbc:mysql://194.5.156.94:3306/u843360242_tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","u843360242_tukule","cocaine");
            pst = con.prepareStatement(query2);
            rs=pst.executeQuery();
            DefaultTableModel tm=(DefaultTableModel)analyticsTable.getModel();
            tm.setRowCount(0);
         while(rs.next()){
                int id = rs.getInt("stock.id");
                int current = rs.getInt("stock.Quantity");
                String name = rs.getString("stock.Name");
                String price = rs.getString("stock.Price");
                String query = "SELECT sum(Quantity) as 'sum' FROM `orders` WHERE Created_at >= DATE(CURRENT_DATE() -7) 
                and Stock_id ="+id; 
                try {
               con = DriverManager.getConnection("jdbc:mysql://localhost:3306/u843360242_tukule 
         useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");
               pst = con.prepareStatement(query);
               rs=pst.executeQuery();
               rs.next();
                   if(rs.getInt("sum") > 0)
                {
                  ordered = rs.getInt("sum");
                  initial = current + ordered;
                }
                else{ 
                  ordered = 0;
                  initial = current + ordered;
                }
                   Object o[]={
                            name,
                            price,
                            initial};
                   tm.addRow(o); 
               } catch (SQLException ex) {
                   Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
               }     
           }             
     } catch (SQLException ex) {
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
     }  
}   

您正在为外部和内部结果使用结果集 rs。 使用内部结果集重新初始化 rs 会影响您的外部循环条件。 即使 rs 中仍有行由于循环进行,读取 id, quantity, name 等列将导致异常,因为新结果集 rs 中可能不存在列。