JDBC - Getting tables from database

You can retrieve all tables from database using JDBC. DatabaseMetaData object contains various method to get the meta information from any database. This object can be accessed by invoking getMetaData() on the Connection object.


DatabaseMetaData dbmd=con.getMetaData();
 After getting the DatabaseMetaData, you can use it to retrieve the tables from any database like following statement,

ResultSet rs=dbmd.getTables(null,null,null,new String[]{"table"});
Here, you will get the ResultSet Object containing various other information like Schema, catalog, table name, etc. Table name available in third column of this ResultSet so we can get it as rs.getString(3);

To get all tables from a database using Connection, we need to traverse entire ResultSet object. We have to invoke rs.next() till it returns false and on each invocation of rs.next(), get the data from third column to get the name of the table.

Here is a method that returns the array of table names from the database connection.



 public String[] tables()throws Exception
{
           DatabaseMetaData dbmd=con.getMetaData();
           ResultSet rs=dbmd.getTables(null,null,null,new String[]{"table"});
           String tablesNames="";
           while(rs.next()){
                   //retrieving table name and concating it to string  tablesNames using comma as a separator between names        
                   tablesNames=tablesNames+rs.getString(3)+",";
           }
            // getting array of table names from comma separated tableNames String
           String names[]=tablesNames.split(",");
           return names;
}   





No comments:

Popular Posts