Java Tips Weblog

  • Blog Stats

    • 2,571,520 hits
  • Categories

  • Archives

Table From Database

Posted by Rob Camick on March 12, 2009

A JTable is frequently used to display data retrieved from a database. The JDK does not support this directly but there are a couple of standard ways to implement this functionality:

  • use the ResultSet to implement the TableModel interface
  • copy the data from the ResultSet to an existing TableModel

For the first approach, just search the web using “ResultSetTableModel” and you will find many different implementations. The trick will be to find an implementation with all the features you require, or one you can customize to meet your requirements.

For the second approach, you can use the DefaultTableModel, or you may find it easier to use the ListTableModel introduced in a previous blog entry..

The ListTableModel is now easier to use to meet this requirement as I have added new functionality to the class. A static method, createModelFromResultSet(…) has been added. You can now create the model and table in two lines of code:

ListTableModel model = ListTableModel.createModelFromResultSet( resultSet );
JTable table = new JTable( model );

Of course it is still up to you to create the SQL and execute the query to create the ResultSet, but creating the model and table couldn’t be any easier. A few things to know about the created model:

  • the headings will automatically be formatted (ie. a column name of “PostalCode” will be formatted to “Postal Code”).
  • by default the model will be uneditable (although this is easily changed at the model or column level using methods inherited by the ListTableModel).
  • the column class is set appropriately for each column (ie. “Id” is rendered right justified as a number).

table-from-database

For a simple example of how to use the DefaultTableModel check out the Table From Database example code posted below. The code will use the ResultSet to create a Vector of column names as well as a Vector containing the data for each row and column. The DefaultTableModel is then created using these Vectors. Then by overriding the getColumnClass() method of the JTable you can have the table choose the appropriate renderer and editor for each column of data.

Get The Code

ListTableModel.java
RowTableModel.java
Table From Database Example

See Also

List Table Model
Row Table Model

Related Reading

How to Use Tables
JDBC Database Access

37 Responses to “Table From Database”

  1. Tadeo said

    Well as you said:
    “…creating the model and table couldn’t be any easier.”

    I’m new in Java programing, and very new to Swing, I’m writing my first GUI project, so your codes are really helpful, how could I give you the credit for the model?, maybe in the about of the GUI?, and finally, could you give a hint to write something to order the rows by clicking the column header like in the example of the BeanTabelModel?

    PD Sorry if I misspelled something.

  2. Caesar Were said

    Thank you very much for your solution. It has solved my problem.

  3. Tadeo said

    Hi again, I noticed that when I use a time field in MySQL it is correctly shown in the MySQL console, but when I try to use your model that field isn’t shown as time should like HH:MM:SS, it is shown as a date DD/MM/YY, how can I change that?.

  4. Ken said

    This model seems to solve my needs…creating a custom table model for data retrieved from a mySql database.
    I will change the driver accordingly. I understand SQL very well and was Oracle certified but I am changing from VB to Java after several years off.
    I assume that with this model, I can add action listeners to a textbook or combobox to filter the data in this model. Are there threads for Filtering data using this type of tablemodel?

    PS It looks like from your formatting of the Postal Code that you are in Canada.

    • Rob Camick said

      Sorting and filtering should work on any properly implemented TableModel. Read the JTable API and follow the link to the Swing tutorial on “How to Use Tables” for working examples.

      • Ken said

        Thanks for your reply.

        I have read the Swing Tutorial and others on the topic and they all have one thing in common…they build the model by hardcoding it and the include their model as a parameter creating a custom table model.
        When you are using a recordset/resultset the query builds the table, and in all examples that I have tried, create a default table model…which the tutorials say will not work with filtering.

        I need to crete tables that actually reflect the records in database in real time.
        Specifically how do you change the table model when you create a table from a resultset so that I can apply the Filtering actionevent/listener?

      • Rob Camick said

        A TableModel is a TableModel. It doesn’t matter if the data is hard coded or dynamically loaded. The sort/filter methods work on the data in the TableModel. So yes a DefaultTableModel will work. I gave you a link to the tutorial. Change the example to use a DefaultTableModel. If you can’t get it to work then post a SSCCE on a forum and I’m sure you will get help. Once you understand the basics using the DefaultTableModel you should then be able to use the ListTableModel presented here.

      • Evan said

        First I want to say thank you for your work. It’s really helped me to not only figure out what I need to do to get things to work in my program but also a better understanding of JTables/Swing in general.

        Anyway I was replying because I have to agree with Ken. The model and everything will solve my needs but I can’t seem to get the results to filter. I soon as I plug in the ListTableModel into a RowSorter to filter it just doesn’t work I don’t even receive any errors? The table just doesn’t change. I thought I had a good understanding…You know usually I do but it’s always some very TINY mistake. Anyway I was wondering if you could ever do a blog post about filtering your ListTableModel? Or pointing me in the right direction I’ve tried looking in various places including the “How to use Tables”

      • Rob Camick said

        Start with the TableFilterDemo from the Swing tutorial. Rename all references to the “MyTableModel” with “ListTableModel”. Replace the line of code that creates the MyTableModel, with the 7 lines of code from the ListModel blog that gives a simple example of how to create a ListTableModel.. The idea is to start with filtering code that works and just replace the couple of lines of code that create or reference the MyTableModel with you new custom TableModel which in this case happens to be the LIstTableModel.

      • Evan said

        Yeah I did that but it didn’t work at first. It turned out somehow I turned the model’s pointer to null. When I started over again using small bytes of my code and reworked it all it went fine. Thanks for all your help. This blog is extremely helpful!!

  5. Adam said

    Your codes, showing how to coy data table contents of a database to jTable is just amazing, easy to understand and error free. I used it to read MSSQL Database table without any roblem. Thank you from inner of my heart and you are really helpful to millions of cyber space community members, who are interested to learn database manipulation. Thank you for your time again.

  6. Mohan said

    Thank u very much…. I stopped here my searching for my doubts and the way u gave the code is really good(as per my knowledge…..i’m a beginner……thank u very much.. Also i added this site to my favorites…

  7. Thank you, Thank you, Thank you!!!! I tried for weeks to get something to work – this did it in the few minutes it took to copy and paste the code. You’re my hero!

  8. clark said

    Your example uses some obsolete collections. It would be more useful if it used object arrays instead.

  9. Anonymous said

    I think you should not put the code that populates the model inline in the same thread that creates the GUI. What if you have 1M rows to populate? Then your GUI will become unresponsive. I think you should implement swingworker in populating the table to make it parallel to the EDT. That being said, I think you should pass only the string query to the model, because if you take care the connection management outside the model, since resultset is processed in swingworker, then you have no guarantee if the swingworker is done reading the resultset before the freeing the resources (resultset.close & statement.close & connection.close). I think its better to do the creation of connection inside the model, use the passed string query, then from there, get the resultset. This way, you can just put the codes for freeing resource in the done() method of the swingworker which guarantess the reading of resultset to be done.

  10. Hi Rob,

    I’m not really a Java expert (my skill are more on Oracle database) but I had to help a colleague which was working on an interface to read some data from database. You code makes really easy to fill a table from database.
    Even without much experience I was able to use your code without problem.

    I’ve also appreciated and used TableColumnAdjuster and TableColumnManager.
    Everything was so easy to use.

    Thank a lot for your code.

    Regards.
    Alberto

  11. 2013 now, your code is still helping! Thanks man!

  12. Anonymous said

    thanx for Table From Database Example. it works fine.

  13. Sultan said

    Is it possible to use this with your other article “Table Button Column”? because i want to have a buy-button in my table which gets data from database, can you show an example?

    • Rob Camick said

      This will only work with the TableFromDatabaseExample because you can customize the Vectors to hold an extra column in the headings and in the data Vectors. You can’t use the RowTableModel for this.

      • Sultan said

        Is it possible in any way to have a jButton in a jTable using your class ListTableModel or in any other way?

  14. Sultan said

    Hello again Rob, this time i am having trouble updating a jTable when i insert in database, so i want the table to update in runtime. i have tried with table.repaint and also with making a new model with ResultSet which i inserted as parameter for createTableWithResultSet method, everytime i try to update i get a nullpointerexception when the program enters the update method.

    do you have any idea why this is happening and what i can do?

    i am using your ListTableModel to get data from database and insert in jTable.

    any help will be appreciated

  15. Anonymous said

    thanks sir i will bookmark your site

  16. Ki Vok said

    pk il m’affiche just la 1er ligne :(

  17. schnee said

    Hello, thank you sooo much, it works! one small issue with mine, the table headers do not display, what could be the reason for this?

    • Rob Camick said

      This has nothing to do with this class. You must add the JTable to a JScrollPane and add the scroll pane to the frame in order for the headings to be displayed.

  18. schnee said

    Thanks, i figured it out by setting the parameters of the Jscrollpane correctly. Thanks! Truly helpful!

  19. nice share :)
    gonna use it in my code

  20. Hassan said

    Hi, I used the code you provided in example: Table From Database Example (http://www.camick.com/java/source/TableFromDatabase.java);
    But I’m having a problem: Every time I run the code, it throws following exception “java.sql.SQLException: Column not found: 0”.
    Help me please.

Leave a comment