Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

Without knowing much about what's going on here simply trying to connect to a database that doesn't exists should throw a TimeoutException error or something similar. Just catch the exception and do stuff if you cannot connect.

boolean canConnect = false;
Connection conn = null;
try{
    conn = DriverManager.getConnection(...);
    canConnect = true;
}(Exception ex){
   canConnect = false;
}

if (!canConnect){
  makeDatabase(...);
}

Enjoy your day!

try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/", "root", "admin");
        Statement statement = connection.createStatement();
        String sql = "CREATE DATABASE IF NOT EXISTS DBNAME";
        statement.executeUpdate(sql);
    } catch (ClassNotFoundException | SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Kindly Note a Two things

  1. The new driver class is `com.mysql.cj.jdbc.Driver'
  2. The query CREATE DATABASE IF NOT EXISTS DBNAME means you dont have to check if database exits
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top