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:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment