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){
                DefaultTableModel dtm = new DefaultTableModel();
                ResultSetMetaData meta = rs.getMetaData();
                int col = meta.getColumnCount();

                int row = rs.getRow();

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

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


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

                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);

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