2014-02-27 94 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