简体   繁体   中英

Connecting to PostgreSQL on Amazon EC2 through Java

I want to connect to PostgreSQL database in java, which is on Amazon EC2. I can connect to it using a postgres client on Mac called Postico. I specify next info:

  1. Nickname

  2. Host (ec2-xx-xx-xx-xx.xx-xx-x.compute.amazonaws.com)

  3. User

  4. Password

  5. Database name

  6. SSH host

  7. User

  8. Password - blank

  9. Private key - .pem file

I could not find any example about how to connect it in Java. I found some RedshiftJDBC driver and added it to project. than I tried this:

try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("Where is your MySQL JDBC Driver?");
            e.printStackTrace();
            return;
        }
        System.out.println("MySQL JDBC Driver Registered!");
        try {
            this.connection = DriverManager.getConnection("jdbc:postgresql://" +DNS+"/"+myDBname, MYSQLUSER, MYSQLPW);
        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
        }

        if (connection != null) {
            System.out.println("You made it, take control your database now!");
        } else {
            System.out.println("Failed to make connection!");
        }

I knew it would not work, but at least I tried)) I have no idea how to specify Private key in request (how to send it), or whatever. Could someone help me ? Thank you.

Try this the below code with PostgreSQL JDBC driver. You want to make the code a bit more resilient (eg check db for null in-between connecting and sending a query, etc.), but this should get you going.

private final String DB_HOST = "YOUR_EC2_HOSTNAME";
private final String DB_PORT = "5432";
private final String DB_USER = "YOUR_POSTGRES_USERNAME";
private final String DB_PASSWD = "YOUR_POSTGRES_PASSWORD";
private final String DB_NAME = "YOUR_POSTGRES_DBNAME";
private final String DB_URL = "jdbc:postgresql://" + DB_HOST + ":" + DB_PORT + "/" + DB_NAME;

private final String INSERT = "INSERT INTO articles (date, name, uuid) VALUES (?, ?, ?)";
private Connection db = null;

public PostgreSQLService() {
    try {
        Class.forName("org.postgresql.Driver");
        db = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWD);
    } catch (ClassNotFoundException | SQLException ex) {
        log.error(ex);
    }

    try (PreparedStatement st = db.prepareStatement(INSERT)) {
        st.setEscapeProcessing(false);

        st.setDate(1, new java.sql.Date(DateUtil.getToday().getTime()));
        st.setString(2, "YOUR_NAME");
        st.setObject(3, UUID.randomUUID());

        if (st.executeUpdate() <= 0) {
            throw new PostgreSQLServiceException("0 rows inserted while trying to insert a new row ::: " + st.toString());
        }

    } catch (SQLException sqle) {
        throw new PostgreSQLServiceException("Received an SQLException trying to insert a row", sqle);
    }
}

The Maven dependency is:

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.4.1208</version>
</dependency>

Note, you need to open up port 5432 in that EC2 instance's security group if you're executing this code from outside AWS.

I would also suggest looking at Amazon RDS. You can connect to it with the above code just the same as a Postgres instance running on EC2.

I hope this helps!

You don't specify that SSH info (SSH host, private key, etc.) when connecting from Java. The JDBC driver expects to be able to connect directly to the database server and does not support SSH tunneling. If you need to use SSH tunneling then you would have create that connection separately before starting the Java application.

If the Java application is running on AWS then you should be able to configure the network to allow a direct connection. If you are testing your Java application locally and need to connect to the remote database, then you run the ssh command locally to open a tunnel first. See this documentation: http://www.postgresql.org/docs/8.2/static/ssh-tunnels.html or this answer: PostgreSQL via SSH Tunnel

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