Binding jTable with Database

Binding jTable with Database

Binding jTable with Database

In Binding jTable with Database, you need to build a method which returns a model with a resultset object as a parameter and then set the model of the jTtable with the method i.e jTable2.setModel(buildTableModel(rs));

the code snippet for the method that builds the table model is as follows;

public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {

ResultSetMetaData metaData = rs.getMetaData();

// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) { columnNames.add(metaData.getColumnName(column)); } // data of the table Vector<Vector<Object>> data = new Vector<Vector<Object>>(); while ( { Vector<Object> vector = new Vector<Object>(); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { vector.add(rs.getObject(columnIndex)); } data.add(vector); } return new DefaultTableModel(data, columnNames); }

After implementing the above method in your class you execute your query and store it in a resultset object (as usual) then use the resultset object to run the following code

stmt = connection.createStatement();
rs = stmt.executeQuery("select * from user");

As above you can see how the resultset object is inserted into the table using the buildTablemodel method

Thank you, if you have any questions, kindly post below