Kostas Drak
Kostas Drak

Reputation: 3260

Cannot connect Java to external mysql database

Hello i am currently building a programm that register users to mysql database. Everything works fine on localhost but when i try to connect to external database it gives me an error such as this below.

enter image description here

I have granted all privileges to the user in the database i am trying to acess and also i have the driver installed. Any ideas??

My code:

private void createEventListenerDBProperties() {
        dbSubmitBtn.addActionListener((ActionEvent e) -> {
                if (dbDriverChooser.getSelectedItem().equals("com.mysql.jdbc.Driver")) {
                  driver = (String) dbDriverChooser.getSelectedItem();
                  port = dbPortField.getText();
                  host = "jdbc:mysql://" + hostField.getText() + ":" + port + "/";
                  db = dbnameField.getText();
                  dbuser = dbUsernameField.getText();
                  dbpassword = new String(dbPasswordField.getPassword());
                }
            }
        });
    }

    private Connection instanciateDB() {
        Connection con = null;
        try {
            Class.forName(driver);
            con = DriverManager.getConnection(host + db, dbuser, dbpassword);
            System.out.println("Connection Established");
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println("Connection not Established");
            JOptionPane.showMessageDialog(Project2.this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        return con;
    }

Upvotes: 2

Views: 156

Answers (1)

giorgos
giorgos

Reputation: 37

I think your way to connect is wrong. Instead of this:

con = DriverManager.getConnection(host + db, dbuser, dbpassword);

try this:

con = DriverManager.getConnection(host + db + "?user=" +  dbuser + "&password=" +dbpassword);

Check this out, it may be useful. http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-connect-drivermanager.html

Upvotes: 1

Related Questions