从多个sqlite表中填充Jtable

时间:2017-03-19 11:53:58

标签: java sqlite

我有三个数据库表及其各自的列,如下所示:

studentinfo :( studentid,姓名) 余额:(学生,平衡) 金额:(学生,金额)

我想直接从数据库中显示JTable上的studentid,name,balance,amount。我从表中检索这些信息并存储在Map中,然后在JTable上显示。但正如你在附带的输出图片中看到的那样,值在我的JTable上不断重复。 这是我的代码:

string ="select studentinfo.studentid,name,balance,amount from studentinfo     inner join Balance on studentinfo.studentid = Balance.studentid inner join Amount on studentinfo.studentid = Amount.studentid"        
  while(rs.next()){                
       for(i = 0, k=1,p=2,m=3; i < 1 && k < 2 && p<3 && m<4; i++,k++,p++,m++)  //JTable colums
        {
           for(j = 0; j < rs.getRow(); j++)  // Jtable rows
           {           
           id = rs.getString("studentid");
           name = rs.getString("name");   
           amt = rs.getDouble("amount");
           bal = rs.getDouble("balance"); 

           map1.put(id, name);
           map2.put(id, amt);
           map3.put(id, bal);                     
          }
          j--   // change the value of j=0 to always start from the first row of a new column in the JTable;


                Set set = map1.entrySet();
                Iterator iterator = set.iterator();
                while(iterator.hasNext()) {
                Map.Entry ent = (Map.Entry)iterator.next();
                table.setValueAt(ent.getKey(), j, k);
                table.setValueAt(ent.getValue(), j, i);
                }

                Set set1 = map2.entrySet();
                Iterator iterator1 = set1.iterator();
                while(iterator1.hasNext()) {
                Map.Entry ent1 = (Map.Entry)iterator1.next();
                table.setValueAt(ent1.getValue(), j, p);
                }

                Set set2 = map2.entrySet();
                Iterator iterator2 = set2.iterator();
                while(iterator2.hasNext()) {
                Map.Entry ent2 = (Map.Entry)iterator2.next();
                table.setValueAt(ent2.getValue(), j, m);
                }
       }

}

输出:

Output table

1 个答案:

答案 0 :(得分:1)

问题是因为你一遍又一遍地在同一行上迭代,我认为你使事情变得复杂,如果你将值设置为table,代码可以简单得多,如下所示:

int rowCount=0;
while(rs.next()){   
    table.setValueAt(rs.getString("studentid"),rowCount, 0);
    table.setValueAt(rs.getString("name"), rowCount, 1);
    table.setValueAt(rs.getDouble("amount"), rowCount, 2);
    table.setValueAt(rs.getDouble("balance"), rowCount, 3);

    rowCount++;//increment the row count for each row fetched
}