2014-02-27 95 views
14

我将用一个简单的java程序连接到我的heroku Postgres数据库。但是,如果我尝试连接,我得到一个错误。任何人都可以解释我的问题或可以解决这个问题吗?无法连接到heroku PostgreSQL db

THX:d

代码:

public static void main(String[] args) throws InstantiationException, 
     IllegalAccessException, ClassNotFoundException { 
    System.out.println("-------- PostgreSQL " 
      + "JDBC Connection Testing ------------"); 
    try { 
     Class.forName("org.postgresql.Driver"); 
    } catch (ClassNotFoundException e) { 
     System.out.println("Where is your PostgreSQL JDBC Driver? " 
       + "Include in your library path!"); 
     e.printStackTrace(); 
     return; 
    } 
    System.out.println("PostgreSQL JDBC Driver Registered!"); 
    Connection connection = null; 
    try { 
     // ========>  from heroku website 
     String url = "jdbc:postgresql://ec2-107-20-214-225.compute-1.amazonaws.com:5432/databasename"; 
     Properties props = new Properties(); 
     props.setProperty("user", "someusername"); 
     props.setProperty("password", "somepassword"); 
     props.setProperty("ssl", "true"); 
     connection = DriverManager.getConnection(url, props); 
    } catch (SQLException e) { 

     System.out.println("Connection Failed! Check output console"); 
     e.printStackTrace(); 
     return; 
    }... 

输出:

-------- PostgreSQL JDBC Connection Testing ------------ 
PostgreSQL JDBC Driver Registered! 
Connection Failed! Check output console 
org.postgresql.util.PSQLException: The connection attempt failed. 
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:225) 
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:64) 
    at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:138) 
    at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:29) 
... 
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) 
    ... 
+4

请参阅:http://stackoverflow.com/questions/9386803/problems-conne cting-pentaho-kettle-spoon-to-heroku-postgresql -using-ssl和这里:http://stackoverflow.com/questions/11832361/how-to-setup-spring-heroku-postgres-ssl-datasource –

回答

21

感谢卢卡斯Eklund的!

我的网址应该是这样的:

String url = "jdbc:postgresql://ec2-107-20-214-225.compute-1.amazonaws.com:5432/databasename 
?user=someusername&password=somepassword 
&ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory"; 
+2

解决方法通过不验证证书是不是从安全的角度来看不是很好... –

+0

请参阅https://jdbc.postgresql.org/documentation/head/ssl-client.html文档如何正确设置它包括要验证的证书 – Markus

6

添加sslmode到数据库网址:

字符串URL = “的jdbc:在PostgreSQL:// ec2-107-20- 214-225.compute-.amazonaws.com:5432/databasename?sslmode=require