简体   繁体   中英

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

I am trying to connect to an AWS DB, but I am getting the following exception and error while I run the program above:

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.

Is it error in the hostname I am trying to connect to?

Based on the connection string and URL of the database, I see that you are connecting to the database installed in EC2. I assume that you are trying to connect to instance from / via external internet.

Please check the following settings

  1. Check if the port 3306 is open for the instance for the TCP protocol to your public IP in the security group used by the instance
  2. You need to enable remote connection in your MySQL. It is a database instance level setting.

The best litmus test to confirm whether it is problem of connection / connectivity setting is to try running the above code inside the same ec2 instance in which the database instance is connected.

Seems that you have to open port 3306 to the world (which is not a good idea by the way and you may want to revise this in production). To do that you need to

  1. add a permissive rule to security group set for EC2 instance with running MySQL server.
  2. Open port on firewall that is running on instance (if any)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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