Sunday, June 20, 2021

Java Program to Get All DB Schemas

In this post we’ll see a Java program to list all the schemas in a DB. Database used here is MySQL.

List all DB schemas using Java

To get all the database schemas in Java you can use the getCatalogs() method provided by the DatabaseMetaData interface in the JDBC API.

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBMetaData {
  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("com.mysql.jdbc.Driver");
      // Creating connection
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306", 
                        "root", "admin");
      // Getting DatabaseMetaData object
      DatabaseMetaData dbMetaData = connection.getMetaData();
    
      // getting Database Schema Names
      ResultSet rs = connection.getMetaData().getCatalogs();
      while (rs.next()) {
        System.out.println("Schema Name - " + rs.getString("TABLE_CAT"));
      }
      
   } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }finally{
      if(connection != null){
       //closing connection 
       try {
         connection.close();
       } catch (SQLException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
      } // if condition
    }// finally
  }
}

Two points to note here are-

  • In the DB URL you are providing for connection, you don’t have to provide any specific schema. So your URL would be like this– jdbc:mysql://localhost:3306
  • getCatalogs() method returns a resultset which has only one column “TABLE_CAT” so you can use that column to get value or column index as 1 to get the value. i.e. rs.getString("TABLE_CAT") or rs.getString(1). By iterating through that result set you can get the list of all DB schemas.

That's all for this topic Java Program to Get All DB Schemas. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Program to Get All The Tables in a DB Schema
  2. Connection Pooling Using Apache DBCP in Java
  3. Connection Pooling Using C3P0 in Java
  4. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  5. CallableStatement Interface in Java-JDBC

You may also like-

  1. Remove Duplicate Elements From an Array in Java
  2. Convert float to String in Java
  3. Configuring DataSource in Spring Framework
  4. Spring JdbcTemplate Insert, Update And Delete Example
  5. Garbage Collection in Java
  6. Java Stream API Tutorial
  7. ConcurrentHashMap in Java With Examples
  8. Synchronization in Java - Synchronized Method And Block