Java ResultSet to JTable

How to Show Java ResultSet to JTable?

First, let me write some requirements for this post

  1. mysql-connector-java-5.1.x.jar (as a library for connecting mysql dan java)
  2. Some import
    import java.sql.ResultSet;
    import javax.swing.table.DefaultTableModel;
    

And here is the method

    public static DefaultTableModel ResultSet2TableModel(ResultSet rs){
        try{
                DefaultTableModel dtm = new DefaultTableModel();
                ResultSetMetaData meta = rs.getMetaData();
                int col = meta.getColumnCount();

                rs.last();
                int row = rs.getRow();
                rs.beforeFirst();

                Object[] rowData = new Object[col];
                Object[] colData = new Object[col];

                for (int i=0;i<col;i++){
                    colData[i] = meta.getColumnLabel(i+1);
                }

                dtm.setColumnIdentifiers(colData);

                for (int i=0;i<row;i++){
                    rs.next();
                    for (int j=0;j<col;j++){
                        rowData[j] = rs.getString(j+1);
                    }
                    dtm.addRow(rowData);
                }

                return dtm;
        } catch (Exception ex){
            JOptionPane.showMessageDialog(null, "ResultSet to TableModel Converter : "+ex.getMessage());
            return null;
        }
    }

The return value is DefaultTableModel, you can use it like

ResultSet rs = con.executeQuery(sql);
DefaultTableModel dtm = ResultSet2TableModel(rs);
myJTable.setModel(dtm);

Note : I’m Using

  1. NetBeans IDE 6.7
  2. JDK 7
  3. mysql-connector-java-5.1.6.jar
  4. Windows XP SP3 Operating System

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation