Karan Malhotra
Karan Malhotra

Reputation: 145

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.

Upvotes: 1

Views: 620

Answers (2)

camickr
camickr

Reputation: 324207

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

Upvotes: 2

Karan Malhotra
Karan Malhotra

Reputation: 145

Vector columnNames = new Vector();
    columnNames.addElement("Table");

    DefaultTableModel model = new DefaultTableModel(columnNames, 0);
    try{con = DriverManager.getConnection("your url");
        String[] types = {"TABLE"};
        DatabaseMetaData metadata = con.getMetaData();
        ResultSet resultSet = metadata.getTables(null, null, "%", types);


            while (resultSet.next()) 
            {

                Vector row = new Vector();
                row.addElement( resultSet.getString(3) );
                model.addRow(row);
            }

            table = new JTable(model  );
            scrollPane = new JScrollPane( table );
            scrollPane.setBounds(10, 11, 724, 639);
            contentPane.add( scrollPane );
            scrollPane.setViewportView(table);

thanks to @camickr for the code. i will not figure this out without your help. thanks man

Upvotes: 1

Related Questions