简体   繁体   中英

Retrieving Data from database to JTable in java

I want to fetch some data from a database and display it in a JTable . But this code is not working - it compiled successfully but doesn't give any output. What could be the issue? I'm new to Java, so please explain in detail.

try
{
    DefaultTableModel dtm=new DefaultTableModel();
    dtm.addColumn("RegNo");
    dtm.addColumn("Student Name");
    dtm.addColumn("Group Name");
    dtm.addColumn("College");
    dtm.addColumn("Phone No");
    dtm.addColumn("Events");
    dtm.addColumn("Event Category");
    dtm.addColumn("Amounts");
    String str="select * from robomaze;";
    ResultSet rs=DBConnect.st.executeQuery(str);
    int r=0,c=0;
    while(rs.next())
    {
        Class cTypes[]= {String.class,String.class,String.class,String.class,BigInteger.class,String.class,String.class,Integer.class};
        dtm.addRow(cTypes);
        c=0;
       dtm.setValueAt(rs.getInt(1), r, c);
         c++;
          dtm.setValueAt(rs.getInt(2), r, c);
         c++;
          dtm.setValueAt(rs.getInt(3), r, c);
          c++;
          dtm.setValueAt(rs.getInt(4), r, c);
          c++;
          dtm.setValueAt(rs.getInt(5), r, c);
          c++;
          dtm.setValueAt(rs.getInt(6), r, c);
          c++;
          dtm.setValueAt(rs.getInt(7), r, c);
          c++;
          dtm.setValueAt(rs.getInt(8), r, c);
          r++;
    }
    jtable1.setModel(dtm);
    DBConnect.con.close();

}catch(Exception en)
{
    JOptionPane.showMessageDialog(rootPane, en);
}

Given....

dtm.addColumn("RegNo");
dtm.addColumn("Student Name");
dtm.addColumn("Group Name");
dtm.addColumn("College");
dtm.addColumn("Phone No");
dtm.addColumn("Events");
dtm.addColumn("Event Category");
dtm.addColumn("Amounts");

and...

Class cTypes[]= {String.class,String.class,String.class,String.class,BigInteger.class,String.class,String.class,Integer.class};

it is unlikely that using getInt for each column value is going to work, instead, you might need to use something more like...

while (rs.next()) {
    Object[] rowData = new Object[8];
    rowData[0] = rs.getString(1);
    rowData[1] = rs.getString(2);
    rowData[2] = rs.getString(3);
    rowData[3] = rs.getString(4);
    rowData[4] = rs.getInt(5);
    rowData[5] = rs.getString(6);
    rowData[6] = rs.getString(7);
    rowData[7] = rs.getInt(8);
    dtm.addRow(rowData);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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