Tuesday, February 23, 2010

Display any ResultSet in a JTable

I have created an extension of JTable, called ResultSetTable, to display any SQL ResultSet. It first gets the column names by looking at the meta data of the result set and then builds the table.
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 * A JTable used to display a SQL ResultSet.
 * @author fahdshariff
 *
 */
public class ResultSetTable extends JTable{

  private final DefaultTableModel dataModel;

  public ResultSetTable(ResultSet rs)
                       throws SQLException{

    super();
    dataModel = new DefaultTableModel();
    setModel(dataModel);

    try {
      //create an array of column names
      ResultSetMetaData mdata = rs.getMetaData();
      int colCount = mdata.getColumnCount();
      String[] colNames = new String[colCount];
      for (int i = 1; i <= colCount; i++) {
        colNames[i - 1] = mdata.getColumnName(i);
      }
      dataModel.setColumnIdentifiers(colNames);

      //now populate the data
      while (rs.next()) {
        String[] rowData = new String[colCount];
        for (int i = 1; i <= colCount; i++) {
          rowData[i - 1] = rs.getString(i);
        }
        dataModel.addRow(rowData);
      }
    }
    finally{
      try {
        rs.close();
      }
      catch (SQLException ignore) {
      }
    }
  }
}

14 comments:

  1. Sajan2:00 AM

    Hello Fahd. I have been breaking my head for almost 2 days and was searching for exactly this. Your Blog is very informative, simple humble and professional ;-) Keep going. Thanks for the info ;-) Saj

    ReplyDelete
  2. can you post the full code with the main method and also the connection. it would be much helpful for the beginners.

    ReplyDelete
    Replies
    1. stmt = conn.createStatement ();
      rset = stmt.executeQuery("YOUR SQL QUERY");
      ResultSetTable rst = new ResultSetTable(rset);
      add(rst);

      Delete
  3. Anonymous8:53 PM

    Very handy, thanks!

    ReplyDelete
  4. Anonymous4:12 AM

    Thanks!

    ReplyDelete
  5. dondell8:52 PM

    can this retrieve images?

    ReplyDelete
  6. Anonymous8:27 PM

    nice.

    ReplyDelete
  7. Thanks that seem like the code i need. I yet not applied but still feeling the it is the right one

    ReplyDelete
  8. Hi can this class be changed to work as a method? to be called on an action event?

    ReplyDelete
  9. thanks a lot...
    when you write this info , if you give preview image it will be better solution...

    ReplyDelete
  10. this is awesome. thanks a lot!!

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete