How to list names of all databases in Java
- Details
- Written by Nam Ha Minh
- Last Updated on 31 July 2019   |   Print Email
Sometimes we need to get all database names (schemas or catalogs) available in the database server. To do so in Java with JDBC, you can call the getCatalogs() method of the DatabaseMetaData class. Given an opened database connection, the following code get names of all databases on the server:
DatabaseMetaData metadata = connection.getMetaData(); ResultSet result = metadata.getCatalogs(); while (result.next()) { String aDBName = result.getString(1); System.out.println(aDBName); }
And here is a complete code example – a program that connects to a MySQL database server and prints the names of all schemas/catalogs on the server:
package net.codejava.db; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; public class ListDatabasesProgram { public static void main(String[] args) throws SQLException { String databaseURL = "jdbc:mysql://localhost:3306/"; String username = "root"; String password = "password"; Connection connection = DriverManager.getConnection(databaseURL, username, password); DatabaseMetaData metadata = connection.getMetaData(); ResultSet result = metadata.getCatalogs(); while (result.next()) { String aDBName = result.getString(1); System.out.println(aDBName); } connection.close(); } }
Note that the database URL can point to any database name or just the server’s root as shown in the above code example.
If you know the SQL statement to get database names of the database server, you can execute that statement and read the result. The following code snippet execute the statement “show databases” of MySQL to list all the names of the databases:
String sql = "show databases"; Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql); while (result.next()) { String aDBName = result.getString(1); System.out.println(aDBName); }
This gives the same result as using the database metadata you see previously.
Other JDBC Tutorials:
- How to connect to a database with JDBC
- JDBC CRUD Tutorial
- JDBC Transaction Tutorial
- How to call stored procedure with JDBC
- How to read database metadata in JDBC
- How to insert binary data into database with JDBC
- How to read binary data from database with JDBC
Comments