Skip to content

Instantly share code, notes, and snippets.

@teiolopes
Created March 16, 2015 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teiolopes/61e67a2701e3448e3dc9 to your computer and use it in GitHub Desktop.
Save teiolopes/61e67a2701e3448e3dc9 to your computer and use it in GitHub Desktop.
ResultSet to Jtable
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 (rs.next()) {
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);
}
public static void main(String[] args) throws Exception {
// The Connection is obtained
ResultSet rs = stmt.executeQuery("select * from product_info");
// It creates and displays the table
JTable table = new JTable(buildTableModel(rs));
// Closes the Connection
JOptionPane.showMessageDialog(null, new JScrollPane(table));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment