Most simple code to populate JTable from ResultSet

前端 未结 10 858
慢半拍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条回答
  •  抹茶落季
    2020-11-22 11:47

    Well I'm sure that this is the simplest way to populate JTable from ResultSet, without any external library. I have included comments in this method.

    public void resultSetToTableModel(ResultSet rs, JTable table) throws SQLException{
            //Create new table model
            DefaultTableModel tableModel = new DefaultTableModel();
    
            //Retrieve meta data from ResultSet
            ResultSetMetaData metaData = rs.getMetaData();
    
            //Get number of columns from meta data
            int columnCount = metaData.getColumnCount();
    
            //Get all column names from meta data and add columns to table model
            for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++){
                tableModel.addColumn(metaData.getColumnLabel(columnIndex));
            }
    
            //Create array of Objects with size of column count from meta data
            Object[] row = new Object[columnCount];
    
            //Scroll through result set
            while (rs.next()){
                //Get object from column with specific index of result set to array of objects
                for (int i = 0; i < columnCount; i++){
                    row[i] = rs.getObject(i+1);
                }
                //Now add row to table model with that array of objects as an argument
                tableModel.addRow(row);
            }
    
            //Now add that table model to your table and you are done :D
            table.setModel(tableModel);
        }
    

提交回复
热议问题