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
You may also like-