繁体   English   中英

无法连接到AWS上运行的MySQL数据库

[英]Cannot connect to MySQL database running on AWS

public static void main (String[] args) { 
        String host = "jdbc:mysql://ec2-user@ec2-xx-xxx-xx-xxx.compute-1.amazonaws.com:3306/"; 
        String uname = "root";
        String db = "customers";
        String password = "somepassword";
        String driver = "com.mysql.jdbc.Driver";
        int i = 0;
            try {
                Class.forName(driver).newInstance();
                Connection conn = DriverManager.getConnection(host+db, uname, password); 

                Statement st = conn.createStatement(); 
                i = st.executeUpdate("INSERT INTO users " + 
                        "VALUES ('Simpson1', 'mail@example.com', 'Springfield')"); 

                if(i==1)
                    System.out.println("Sucessfully Updated table");

                conn.close(); 
            } catch (Exception e) { 
                System.err.println("Got an exception! "); 
                System.err.println(e.getMessage()); 
            } 
}

我正在尝试连接到AWS DB,但是当我运行上面的程序时,我收到以下异常和错误:

Got an exception! Communications link failure

The last packet sent successfully to the server was 0 milliseconds
ago. The driver has not received any packets from the server.

我尝试连接的主机名是否有错误?

根据数据库的连接字符串和URL,我看到您正在连接到EC2中安装的数据库。 我假设你正试图从/通过外部互联网连接到实例。

请检查以下设置

  1. 检查端口3306是否为实例使用的安全组中的公共IP的TCP协议实例打开
  2. 您需要在MySQL中启用远程连接。 它是数据库实例级别设置。

确认是否存在连接/连接设置问题的最佳试金石是尝试在连接数据库实例的同一ec2实例中运行上述代码。

似乎你必须向世界开放3306端口(顺便说一下这不是一个好主意,你可能想在生产中修改它)。 要做到这一点,你需要

  1. 通过运行MySQL服务器为EC2实例的安全组集添加一个允许规则
  2. 在实例上运行的防火墙上打开端口(如果有)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM