Most simple code to populate JTable from ResultSet

前端 未结 10 975
慢半拍i
慢半拍i 2020-11-22 11:22

I googled the whole day and no luck. I call getnPrintAllData() method after pressing OK button. So the code is:

public class DatabaseSQLiteConne         


        
10条回答
  •  -上瘾入骨i
    2020-11-22 11:52

    I think this is the Easiest way to populate a table with ResultSet with a method like

    FillTable(MyTable, "select * Customers;");
    

    And a very simple method can be made as

    public void FillTable(JTable table, String Query)
    {
        try
        {
            CreateConnection();
            Statement stat = conn.createStatement();
            ResultSet rs = stat.executeQuery(Query);
    
            //To remove previously added rows
            while(table.getRowCount() > 0) 
            {
                ((DefaultTableModel) table.getModel()).removeRow(0);
            }
            int columns = rs.getMetaData().getColumnCount();
            while(rs.next())
            {  
                Object[] row = new Object[columns];
                for (int i = 1; i <= columns; i++)
                {  
                    row[i - 1] = rs.getObject(i);
                }
                ((DefaultTableModel) table.getModel()).insertRow(rs.getRow()-1,row);
            }
    
            rs.close();
            stat.close();
            conn.close();
        }
        catch(InstantiationException | IllegalAccessException | SQLException e)
        {
        }
    }
    

提交回复
热议问题