You can get the column header dynamically using
ResultSetMetaData
← API linkResultSetMetaData rsMeta = resultSet.getMetaData(); int numberOfCols = rsMeta.getColumnCount(); Vector<String> columnNames = new Vector<>(); // your columns names for (int i = 1; i <= numberOfCols; i++ ){ columnsNames.add(rsMeta.getColumnName(i)); }
You don't need the extra
Vector
or theList
for the data. Just first declare yourDefaultTableModel
with the constructor arguments( Vector/Object[] colNames, int rows)
. Then just use the methodaddRow
from theDefaultTableModel
DefaultTableModel model = new DefaultTableModel(columnNames, 0); while (resultSet.next()) { String data1 = resultSet.getString(1); String data2 = resultSet.getString(2); ... Object[] rowData = new Object[] { data1, data2, ... }; model.addRow(rowData); } return model;
Or, instead of 2., to make sure you're getting the correct number of columns, you could use the Vector inside the
while
loop and loop through the column data.DefaultTableModel model = new DefaultTableModel(columnNames, 0); while (resultSet.next()) { Vector<String> row = new Vector<>(); for (int i = 1; i <= numberOfCols; i++) { row.add(resultSet.getString(i)); } model.addRow(row); } return model;
See more methods and constructors see DefaultTableModel API