无法将Java连接到外部mysql数据库

时间:2014-12-22 01:30:08

标签: java mysql

您好我正在构建一个将用户注册到mysql数据库的程序。在localhost上一切正常但是当我尝试连接到外部数据库时,它会给我一个错误,如下所示。

enter image description here

我已经尝试访问数据库中的用户的所有权限,并且还安装了驱动程序。任何想法??

我的代码:

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;
    }

1 个答案:

答案 0 :(得分:1)

我认为你的联系方式是错误的。而不是:

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

试试这个:

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

检查一下,它可能有用。 http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-connect-drivermanager.html