DataTable equivalent in Java [duplicate]

A similar question that has been asked recently. ResultSet certainly is not a direct equivalent as it only works with an active connection to the database while a DataTable can be used "offline".

From personal experience I would say there is no direct equivalent in Java (haven't tried javax.sql.rowset.WebRowSet, though). You either go with plain SQL and java.sql.ResultSet is your friend. Or you use some ORM tool like Hibernate, Cayenne, Toplink to name a few. Or you build your own (not that I encourage this, but I think on more than one project that has been done successfully).


Give this framework a try:

Casper Datasets

Its a in-memory dataset library that is generic and also type safe. You can:

  • Pull data automatically from relational queries (or from any other programmatic source),
  • Issue complex, chained queries against the dataset,
  • Optimize a given dataset by specifying indexes on particular columns.

Its easy-to-use and doesn't have any significant dependencies. Its also compliant with java.sql.ResultSet, so its possible to integrate this easily into any existing apps that query against relational database


No - not in the standard libraries (i.e. the Java API).


A workaround I've used is JTable. It doesn't have the robust data features of a proper DataTable but it will allow you grab some data and bind it to a control with some structure.

class TableModel extends AbstractTableModel
{
    String[] columnNames = {“FirstName”,”LastName”,”Title”};
    Object[][] rowData= {{‘John,”Smith”,”President”},{“John”,”Doe”,”Employee”}};

    public int getColumnCount()
    {
        return columnNames.length;
    }

    public int getRowCount()
    {
        return rowData.length;
    }

    public String getColumnName(int col)
    {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col)
    {
        return data[row][col];
    }
}

And then to use you simply:

JTable table = new JTable(new TableModel());

Again, this is quick and simple and if you are dealing with large amounts of data I would recommend using a proper ORM tool.


From Standard Library DefaultTableModel is good class.

ResultSet set = s.getResultSet();
        ResultSetMetaData metaData = set.getMetaData();
        int totalColumn = metaData.getColumnCount();
        Object[] dataRow = new Object[totalColumn];
        if(set!= null)
        {
            for(int i=1;i<=totalColumn;i++)
            {
                table.addColumn(metaData.getColumnName(i));
            }
            while(set.next())
            {
                for(int i=1;i<=totalColumn;i++)
                {
                    dataRow[i-1] = set.getObject(i);
                }
                table.addRow(dataRow);
            }

        }