Search code examples
javatry-catchidentifier

Java - Error in code connecting to a MYSQL database try/catch?


I can't for the life of me figure out what the error in my code is. Anyone have any ideas? All the errors are coming in at catch statement about 5 lines from the bottom.

public void connectToDB(){
    try {
    // this will load the MySQL driver, each DB has its own driver
      Class.forName(dbDriver);
      // setup the connection with the DB.
      connect = DriverManager
          .getConnection("jdbc:mysql://localhost/?"
              + "user=root&password=");
    ResultSet resultSet = connect.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);
      if (databaseName.equals("Ballers")) {
          preparedStatement = connect.prepareStatement("DROP DATABASE Ballers");
          preparedStatement.execute();
      }
    }
          ScriptRunner runner = new ScriptRunner(connect, false, false);
          try {
            runner.runScript(new BufferedReader(new FileReader(dumpPath)));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } catch (ClassNotFoundException | SQLException e) {
        System.out.println("not connecting");
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

The text of the errors are as follows:

DatabaseHelper.java:64: <identifier> expected
        } catch (ClassNotFoundException | SQLException e) {
                                       ^
DatabaseHelper.java:64: '{' expected
        } catch (ClassNotFoundException | SQLException e) {
                                         ^
DatabaseHelper.java:64: not a statement
        } catch (ClassNotFoundException | SQLException e) {
                                                       ^
DatabaseHelper.java:64: ';' expected
        } catch (ClassNotFoundException | SQLException e) {

What identifier is expected? Is this not a valid statement?


Solution

  • You must have an odler version of Java

    Multiple-exception catches are supported, starting in Java 7.You must catch them separately.

    convert

    } catch (ClassNotFoundException | SQLException e) {
            System.out.println("not connecting");
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    

    to

    } catch (ClassNotFoundException  e) {
            System.out.println("not connecting");
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch ( SQLException e) {
            System.out.println("not connecting");
            // TODO Auto-generated catch block
            e.printStackTrace();
        }