Search code examples
javadatabaseswingjtableresultset

How to display table name in database to JTable?


I want to get all table name which is in database and display it in JTable.

It is printing:

con =  DriverManager.getConnection("jdbc:h2:C:/SimpleGST/GST/INVOICES","sa","");
String[] types = {"TABLE"};
DatabaseMetaData metadata = con.getMetaData();
ResultSet resultSet = metadata.getTables(null, null, "%", types);
while (resultSet.next()) {
    String tableName = resultSet.getString(3);
    System.out.println(tableName);
    table.setModel(net.proteanit.sql.DbUtils.resultSetToTableModel(resultSet));
}

It is printing the table names but it's not displaying in the table.


Solution

  • while (resultSet.next()) 
    {
        String tableName = resultSet.getString(3);
        System.out.println(tableName);
        table.setModel(net.proteanit.sql.DbUtils.resultSetToTableModel(resultSet));
    }
    

    You have a while loop that keeps replacing the model with every row of data you read. So all the data from the ResultSet has been read the last time you try to set the model.

    The point of using the resultSetToTableModel(...) method is that is will read all the data from the ResultSet for you and create the TableModel. So there is no need for the while loop.

    You need to replace the above code with a single line of code:

    table.setModel(net.proteanit.sql.DbUtils.resultSetToTableModel(resultSet));
    

    Edit:

    but it show too many other columns .. i just want to display tables

    Then you need to create the table model manually. The code would be something like:

    Vector columnNames = new Vector();
    columnNames.addElement("Table");
    
    DefaultTableModel model = new DefaultTableModel(columnNames, 0);
    
    while (resultSet.next()) 
    {
        Vector row = new Vector();
        row.addElement( resultSet.getString(3) );
        model.addRow(row);
    }
    
    table = new JTable( model );
    scrollPane.setViewportView( table );