14
votes

I am new in 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 what I wanted to do is to create a boolean method to check if students database already exists. If it exists then boolean method would return false otherwise its true then I can create 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?

EDIT 2

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;
}
4
Possible duplicate: stackoverflow.com/questions/838978/… , I doubt there is an API method for this, do the same as in the linked post. - zeller
I don't know much about mysql but I have seen this answer before its just that its not implemented in java its in php i think... but based on kirtan's answer can I placed that SQL statement in a string and then pass it as an argument of Statement? Btw I don't think this is also a duplicate because the link you showed me is asking in mysql. I am looking for a java implementation if there is any. - dimas
You can call the sql query in the accepted answer in a prepared statement... - zeller
Surprise, there is a JDBC API for this! I think the problem is the confusing name of getCatalogs() which returns the database names. - mguymon
In the solution you added in your question, remove the boolean exists = false; line, replace the exists = true; line by return true; and the return exists; line by return false;. It's a more common way to do ;) - sp00m

4 Answers

21
votes

You can get that info from a JDBC Connection using DatabaseMetaData#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();
8
votes
show databases like 'students'

If you get a row back, it exists.

3
votes

In newer versions of MySQL (5 and above) run this query:

SELECT COUNT(*)
FROM information_schema.tables 
WHERE table_schema = '[database name]' 
AND table_name = '[table name]';

If the result is 1 it exists.

In Java JDBC that would look something like this:

// Create connection and statement
String query = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema'[database name]' AND table_name = '[table name]'";
ResultSet rs = stmt.executeQuery(query);                  
rs.next();
boolean exists = rs.getInt("COUNT(*)") > 0;
// Close connection, statement, and result set.
return exists;   
2
votes

You're doing it back to front. The correct technique is to try to create it and catch the exception. The way you want to do it is subject to timing-window problems: it wasn't there when you tested, but it was there when you tried to create it. And you still have to catch the exception anyway.