The examples below show you how to get the available catalog names in MySQL database. The available catalog names can be obtained from the DatabaseMetaData
object by calling the getCatalogs()
method. This method returns a ResultSet
object. We iterate it and get the schema name by calling the getString()
method and pass TABLE_CAT
as the column name.
package org.kodejava.jdbc;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MetadataGetCatalog {
private static final String URL = "jdbc:mysql://localhost";
private static final String USERNAME = "kodejava";
private static final String PASSWORD = "s3cr*t";
public static void main(String[] args) {
try (Connection connection =
DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
// Gets DatabaseMetaData
DatabaseMetaData metadata = connection.getMetaData();
// Retrieves the schema names available in this database
ResultSet rs = metadata.getCatalogs();
while (rs.next()) {
String catalog = rs.getString("TABLE_CAT");
System.out.println("Catalog: " + catalog);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Here is the list of catalog names available in the MySQL database:
Catalog: kodejava
Catalog: musicdb
Catalog: mysql
Catalog: performance_schema
Catalog: sys
Maven Dependencies
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.1.0</version>
</dependency>