简体   繁体   English

通过Java连接到Amazon EC2上的PostgreSQL

[英]Connecting to PostgreSQL on Amazon EC2 through Java

I want to connect to PostgreSQL database in java, which is on Amazon EC2. 我想连接到Amazon EC2上的Java中的PostgreSQL数据库。 I can connect to it using a postgres client on Mac called Postico. 我可以使用Mac上称为Postico的postgres客户端连接到它。 I specify next info: 我指定下一个信息:

  1. Nickname 昵称

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

  3. User 用户

  4. Password 密码

  5. Database name 数据库名称

  6. SSH host SSH主机

  7. User 用户

  8. Password - blank 密码-空白

  9. Private key - .pem file 私钥-.pem文件

I could not find any example about how to connect it in Java. 我找不到有关如何在Java中进行连接的任何示例。 I found some RedshiftJDBC driver and added it to project. 我找到了一些RedshiftJDBC驱动程序并将其添加到项目中。 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. 使用PostgreSQL JDBC驱动程序尝试以下代码。 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. 您想使代码更具弹性(例如,在连接和发送查询之间检查db中是否为null等),但这应该可以帮助您。

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: Maven依赖项是:

<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. 请注意,如果要从AWS外部执行此代码,则需要在该EC2实例的安全组中打开端口5432。

I would also suggest looking at Amazon RDS. 我还建议您查看Amazon RDS。 You can connect to it with the above code just the same as a Postgres instance running on EC2. 您可以使用上面的代码连接到它,就像在EC2上运行的Postgres实例一样。

I hope this helps! 我希望这有帮助!

You don't specify that SSH info (SSH host, private key, etc.) when connecting from Java. 从Java连接时,您无需指定SSH信息(SSH主机,私钥等)。 The JDBC driver expects to be able to connect directly to the database server and does not support SSH tunneling. JDBC驱动程序期望能够直接连接到数据库服务器,并且不支持SSH隧道。 If you need to use SSH tunneling then you would have create that connection separately before starting the Java application. 如果需要使用SSH隧道,则在启动Java应用程序之前,您将单独创建该连接。

If the Java application is running on AWS then you should be able to configure the network to allow a direct connection. 如果Java应用程序在AWS上运行,那么您应该能够配置网络以允许直接连接。 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. 如果要在本地测试Java应用程序并且需要连接到远程数据库,则可以在本地运行ssh命令以首先打开隧道。 See this documentation: http://www.postgresql.org/docs/8.2/static/ssh-tunnels.html or this answer: PostgreSQL via SSH Tunnel 请参阅此文档: http : //www.postgresql.org/docs/8.2/static/ssh-tunnels.html或此答案: 通过SSH隧道的PostgreSQL

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

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