Java DatabaseMetaData getTableTypes() method with example


The getTableTypes() method of the DatabaseMetadata interface is used to find out the type of tables supported by the underlying database.

This method returns a ResultSet object holding the names of table types in each row in String format, under the column TABLE_TYPE.

To get the description DatabaseMetadata object.

  • Make sure your database is up and running.
  • Register the driver using the registerDriver() method of the DriverManager class. Pass an object of the driver class corresponding to the underlying database.
  • Get the connection object using the getConnection() method of the DriverManager class. Pass the URL the database and, user name, password of a user in the database, as String variables.
  • Get the DatabaseMetaData object with respect to the current connection using the getMetaData() method of the Connection interface.

Finally, get ResultSet object holding the names of table types, by invoking the getTableTypes() method.

Following JDBC program establishes connection with MySQL database, retrieves and displays the types of the tables it support.

Example

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseMetadata_getTableTypes {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String url = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(url, "root", "password");
      System.out.println("Connection established......");
      //Retrieving the meta data object
      DatabaseMetaData metaData = con.getMetaData();
      //Retrieving the columns in the database
      ResultSet rs = metaData.getTableTypes();
      System.out.println("Types of tables that the underlying database support: ");
      //Printing the column name and size
      while (rs.next()) {
         System.out.println(rs.getString("TABLE_TYPE"));
      }
   }
}

Output

Connection established......
Types of tables that the underlying database support:
TABLE
VIEW
LOCAL TEMPORARY
raja
Published on 15-May-2019 15:45:39
Advertisements