Search code examples
javamysqljdbc

How to check if a particular database in MySQL already exists using Java


I am new to JDBC, and I wanted to find out if there is a way to check if a particular database already exists in MySQL.

Let's say I wanted to create a database named students. If the students database is already created in MySQL an error message in Eclipse would state that this students database already exists. However, I wanted to create a Boolean method to check if students database already exists. If it exists then the Boolean method would return false, otherwise if it’s true, then I can create the students database.

How do I do these in Java? Are there any methods in JDBC that does this or do I need to code it from scratch?


I followed mguymons suggestion and this is what I came up:

public boolean checkDBExists(String dbName) {

    try {
        Class.forName(JDBCDriver); // Register JDBC driver

        System.out.println("Creating a connection...");
        conn = DriverManager.getConnection(DBURL, USER, PASS); // Open a connection

        ResultSet resultSet = conn.getMetaData().getCatalogs();

        while (resultSet.next()) {

            String databaseName = resultSet.getString(1);
            if(databaseName.equals(dbName)) {
                return true;
            }
        }
        resultSet.close();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
    return false;
}

Solution

  • You can get that information from a JDBC Connection using getCatalogs. Here is an example of getting the Catalogs, aka Database names

    // Connection connection = <your java.sql.Connection>
    ResultSet resultSet = connection.getMetaData().getCatalogs();
    
    // Iterate each catalog in the ResultSet
    while (resultSet.next()) {
      // Get the database name, which is at position 1
      String databaseName = resultSet.getString(1);
    }
    resultSet.close();