简体   繁体   中英

Connecting java to MYSQL database in an amazon server

I am trying to connect my java code with mysql DB in amazon rds , i am using this code:

        try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        connection = DriverManager.getConnection(
        "jdbc:mysql://HOST:port_number/DB_name","DB_username", "DB_pass");
        st = connection.createStatement();
        rs = st.executeQuery("SELECT * FROM table name WHERE id = 1");
    } catch (Exception e) {
        System.out.println("DB error : " + e);
    }

i am getting this error when i run it :

DB error : java.sql.SQLException: Unable to connect to any hosts due to exception: java.net.SocketException: java.net.SocketException: Permission denied: connect

** BEGIN NESTED EXCEPTION ** 

java.net.SocketException
MESSAGE: java.net.SocketException: Permission denied: connect

STACKTRACE:

java.net.SocketException: java.net.SocketException: Permission denied: connect
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:143)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:225)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1805)
at com.mysql.jdbc.Connection.<init>(Connection.java:452)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DB.<init>(DB.java:15)
at subgroup.main(subgroup.java:72)


** END NESTED EXCEPTION **

any ideas !!

You need to give access to your machine from where you are trying to read the database.

Also you should grant access to your IP using command prompt.

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html

i rephrase your command because you set the connection variable as drivermanager but in your statement you use con ? and the string inside the connection replace it with the real value for example

connect = DriverManager.getConnection("jdbc:mysql://localhost:3306", "<your DBUsername>", "<your DB Password>");

dont just copy paste next time, learn how the codes work

try {
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection(
        "jdbc:mysql://HOST:port_number/DB_name","DB_username", "DB_pass");
        st = connection.createStatement();
        rs = st.executeQuery("SELECT * FROM table name WHERE id = 1");
    } catch (Exception e) {
        System.out.println("DB error : " + e);
    }

In my case the problem was that I was using a connection from emulator to localhost. If you use emulator to localhost dont use localhost,127.0.0.1 in connection String but use:

10.0.2.2

Hope this helps

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