How to check if a DataBase exist or not after the connection is made JAVA

SanRyu picture SanRyu · Dec 6, 2012 · Viewed 19.5k times · Source

I have a big question... I have a database java program creation.

I want to know if the database exists or not, and the if exists just connect, if not to create it.

I tried this one:

if (dbName.exists() == false) {}

THIS IS ALL THE CODE...

Class.forName("com.mysql.jdbc.Driver");
System.out.println("MySQL JDBC driver loaded ok.");

THIS IS A BACKUP CODE FOR IT, JUST TO WORK FOR NOW.... PARTIAL CODE THAT WORKS !

conn = DriverManager.getConnection(DBurl + url
+ "?createDatabaseIfNotExist=true& + "
+ "useUnicode=true&characterEncoding=utf-8&user="
+ userName + "&&password=" + password);


System.out.println("Connected to database ");           
System.out.println("Connected to the database " + url);

BUT I WANT SOMETHING LIKE:

FILE dbName = new FILE (url);
Statement stmt = new Statement;

if (dbName.exists() == true)
   System.out.println("Database exists ! Connecting ... ");
else {
   String sql = "CREATE DATABASE "+url;
   stmt.executeUpdate (sql);
}

I don't want to put the url with the password and username in the same place... because they are provided from an external part, but that is allready implemented and working.

So I want to rip in 2 peaces, 1 Connect "jdbc:mysql://localhost:3306/"; WITHOUT URL which is the database NAME ... AND THEN IF A DATABASE DOES NOT EXISTS THERE WITH THAT NAME JUST CREATE ON.

It is not working.... not entering in the else more, and says that Exeption Database already exists.

Thanks you very much.

Answer

Udo Klimaschewski picture Udo Klimaschewski · Dec 6, 2012

If it is a MySQL database, the following code should work. Other databases may give a different error code, but the general way should be clear. Important is that you connect to the instance, not a specific database initially. For creating the tables, you will need to connect to the newly created database. You can't use the instance connection that I use in my example for creating the tables:

    Connection connection = null;
    Statement statement = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection("jdbc:mysql://localhost/",
                "root", "admin");
        statement = connection.createStatement();
        String sql = "CREATE DATABASE DBNAME";
        //To delete database: sql = "DROP DATABASE DBNAME";
        statement.executeUpdate(sql);
        System.out.println("Database created!");
    } catch (SQLException sqlException) {
        if (sqlException.getErrorCode() == 1007) {
            // Database already exists error
            System.out.println(sqlException.getMessage());
        } else {
            // Some other problems, e.g. Server down, no permission, etc
            sqlException.printStackTrace();
        }
    } catch (ClassNotFoundException e) {
        // No driver class found!
    }
    // close statement & connection