MySQL is used to manage relational databases, and a single MySQL server can contain many databases for different applications, users, environments, or modules.

In this JDBC tutorial, we shall learn how to list databases in MySQL Server using Java. The most direct way is to connect to the MySQL server through JDBC and execute the MySQL statement SHOW DATABASES;.

JDBC steps to list databases in MySQL Server using Java

Following is the step by step process to list available databases in MySQL Server from a Java program.

  1. Establish connection to MySQL Server
    Create a JDBC connection to the MySQL Server. You do not need to select a particular database in the JDBC URL when your goal is to list all visible databases on the server.
  2. Execute the MySQL database listing query
    SHOW DATABASES; is the SQL statement that returns the list of database names available to the connected MySQL user. Execute this query with the help of the Statement class.
  3. Read database names from ResultSet
    The query returns a ResultSet. Each row contains one database name. The column label is commonly Database, but you may also read the first column by index using getString(1).
  4. Close ResultSet, Statement and Connection
    Once the operation is completed, close the JDBC resources. If you use a modern Java version, prefer try-with-resources, because it closes resources automatically even when an exception occurs.

MySQL Connector/J requirement for JDBC database listing

To run a Java JDBC program with MySQL, add MySQL Connector/J to your project. If you are using Maven, add the dependency to your pom.xml. Use a version supported by your project and Java runtime.

</>
Copy
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

For older Connector/J versions, many examples explicitly load the driver class with Class.forName("com.mysql.jdbc.Driver"). In newer Connector/J versions, the driver class is com.mysql.cj.jdbc.Driver, and JDBC driver auto-loading usually makes the explicit Class.forName() call unnecessary.

Example 1 – List databases in MySQL Server using Java

The complete program to is given below. Replace username and password with credentials you have used while creating a user in MySQL. Also, if the MySQL Server is running on another machine, replace the localhost IP and port with appropriate MySQL Server IP and port.

MySQLDatabaseExample.java

</>
Copy
import java.sql.*;
import java.util.Properties;

/**
 * Program to list databases in MySQL Server using Java
 */
public class MySQLDatabaseExample {

    static Connection conn = null;
    static String username = "username"; // replace with your MySQL client username
    static String password = "password"; // replace with your MySQL client password

    public static void main(String[] args){
        // make a connection to MySQL Server
        getConnection();
        // execute the query via connection object
        executeMySQLQuery();
    }

    public static void executeMySQLQuery(){
        Statement stmt = null;
        ResultSet resultset = null;

        try {
            stmt = conn.createStatement();
            resultset = stmt.executeQuery("SHOW DATABASES;");

            if (stmt.execute("SHOW DATABASES;")) {
                resultset = stmt.getResultSet();
            }

            while (resultset.next()) {
                System.out.println(resultset.getString("Database"));
            }
        }
        catch (SQLException ex){
            // handle any errors
            ex.printStackTrace();
        }
        finally {
            // release resources
            if (resultset != null) {
                try {
                    resultset.close();
                } catch (SQLException sqlEx) { }
                resultset = null;
            }

            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException sqlEx) { }
                stmt = null;
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException sqlEx) { }
                conn = null;
            }
        }
    }

    /**
     * This method makes a connection to MySQL Server
     * In this example, MySQL Server is running in the local host (so 127.0.0.1)
     *  at the standard port 3306
     */
    public static void getConnection(){
        Properties connectionProps = new Properties();
        connectionProps.put("user", username);
        connectionProps.put("password", password);
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(
                    "jdbc:" + "mysql" + "://" +
                            "127.0.0.1" +
                            ":" + "3306" + "/"+
                            "",
                    connectionProps);
        } catch (SQLException ex) {
            // handle any errors
            ex.printStackTrace();
        } catch (Exception ex) {
            // handle any errors
            ex.printStackTrace();
        }
    }
}

Output

information_schema
db1
db2
db3
mysql
performance_schema
sys

List of Databases in MySQL Server.

list databases in mysql server using java - JDBC Tutorial - www.tutorialkart.com
List of databases at MySQL Server

Modern JDBC example to show MySQL databases with try-with-resources

The following version uses try-with-resources. This keeps the code shorter and makes sure the Connection, Statement, and ResultSet are closed automatically.

</>
Copy
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ListMySQLDatabases {

    public static void main(String[] args) {
        String url = "jdbc:mysql://127.0.0.1:3306/";
        String username = "username";
        String password = "password";

        String sql = "SHOW DATABASES";

        try (Connection connection = DriverManager.getConnection(url, username, password);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql)) {

            while (resultSet.next()) {
                System.out.println(resultSet.getString(1));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

This example reads the first column using resultSet.getString(1). That is a safe choice for SHOW DATABASES, because the statement returns a single column containing the database name.

JDBC URL used to connect to MySQL Server before listing databases

For listing databases, the JDBC URL can point to the server without naming a database.

</>
Copy
jdbc:mysql://host:port/

For a local MySQL server running on the default port, the URL is usually:

</>
Copy
jdbc:mysql://127.0.0.1:3306/

If the MySQL server is running on another machine, replace 127.0.0.1 with the server hostname or IP address. If MySQL is using a non-default port, replace 3306 with the configured port number.

MySQL SHOW DATABASES command used by the Java JDBC program

The Java program runs the same MySQL command that you can run from the MySQL client.

</>
Copy
SHOW DATABASES;

In the MySQL command-line client, it would look similar to the following.

</>
Copy
mysql -u username -p -e "SHOW DATABASES;"

The output includes only the databases that the connected MySQL user is permitted to see. Therefore, two users may see different database lists on the same server.

Why some MySQL databases are not displayed in JDBC output

If your Java program does not display an expected database, check the MySQL user privileges first. The connected user must have sufficient privileges to see that database. Also confirm that the program is connecting to the expected MySQL host and port.

  • Wrong server: The JDBC URL may point to another MySQL instance.
  • Wrong port: MySQL may be running on a port other than 3306.
  • Limited privileges: The MySQL user may not have permission to view every database.
  • Old driver configuration: An old Connector/J driver or driver class name may cause connection issues.
  • Authentication issue: Incorrect username, password, or MySQL authentication configuration can prevent the program from connecting.

Reading database names from JDBC ResultSet correctly

When using SHOW DATABASES, the result contains one column. You can read it by column index:

</>
Copy
String databaseName = resultSet.getString(1);

You may also read the column by label in many MySQL setups:

</>
Copy
String databaseName = resultSet.getString("Database");

For small utility programs, getString(1) is simple and avoids confusion if the displayed column label changes across server versions or query forms.

JDBC errors commonly seen while listing MySQL databases

Error or symptomLikely reasonWhat to check
Access denied for userInvalid credentials or insufficient privilegesCheck username, password, host, and MySQL grants
No suitable driver foundMySQL Connector/J is missing from the classpathAdd the Connector/J dependency or JAR file
Empty or incomplete database listUser can see only permitted databasesRun the same query in MySQL client with the same user
Connection refusedMySQL server is not reachableCheck host, port, server status, and firewall
Old driver warningLegacy driver class is usedUse a modern Connector/J dependency and JDBC URL

FAQs on listing MySQL databases using Java JDBC

How do I get a list of databases in MySQL Server using Java?

Connect to the MySQL server using JDBC, create a Statement, execute SHOW DATABASES, and loop through the returned ResultSet. Each row contains one database name.

Do I need to specify a database name in the JDBC URL to show all databases?

No. To list databases, the JDBC URL can point to the MySQL server root, such as jdbc:mysql://127.0.0.1:3306/. You do not have to select a specific database before running SHOW DATABASES.

Why does JDBC show fewer MySQL databases than expected?

MySQL returns the databases visible to the connected user. If the user has limited privileges, the JDBC program may show fewer databases than an administrator account.

Should I use com.mysql.jdbc.Driver or com.mysql.cj.jdbc.Driver?

com.mysql.jdbc.Driver is the older driver class name. With newer MySQL Connector/J versions, the driver class is com.mysql.cj.jdbc.Driver, and explicit driver loading is usually not required because JDBC can auto-load the driver from the classpath.

Can I list MySQL databases without Java?

Yes. You can run SHOW DATABASES; directly in the MySQL command-line client or another MySQL client tool. Java JDBC is useful when the database list has to be read inside a Java application.

Editorial QA checklist for this JDBC MySQL database listing tutorial

  • The Java program connects to the MySQL server, not just to a single selected database.
  • The SQL statement used for listing databases is SHOW DATABASES.
  • The tutorial explains that output depends on MySQL user privileges.
  • Modern JDBC usage with try-with-resources is included for safer resource handling.
  • Code blocks use Java, SQL, XML, Bash, plaintext, syntax, or output classes as appropriate for PrismJS formatting.

JDBC MySQL database listing recap

In this Java Tutorial, we learned how to list databases in MySQL using Java. The main idea is to connect to the MySQL server with JDBC, execute SHOW DATABASES, read each row from the ResultSet, and close JDBC resources properly.