2015-09-04 118 views
0

我試圖使用IBM Bluemix上的SSL連接到DB2數據庫。SSL DB2連接失敗

當我第一次嘗試使用SSL連接時,它不起作用。閱讀完文檔後,我意識到它使用SSL連接到數據庫。

我嘗試使用下面的代碼來得到它連接到數據庫:

public boolean connect() { 
    try { 
    String url = "jdbc:db2://" + serverName + ":" + port + "/" + dbName+ 
       ":securityMechanism=9";  

    connection = DriverManager.getConnection(url, userName, passWord); 
    st = connection.createStatement(); 
    return true; 
    } catch (Exception e) { 
    System.err.println(e.getMessage()); 
    } 

    return false; 
} 

不過我不是關於如何使用具備上述代碼中的SSL證書不太清楚。

我試過尋找例子,但大多數的解釋要麼不清楚,要麼用於其他數據庫系統。

+0

你看到的錯誤信息是什麼?你在使用Liberty buildpack嗎? – whitfiea

回答

1

按照SQLDB documentation,如果您使用最新com.ibm.db2.jcc.DB2Driver與JDBC連接,當前的SSL證書是捆綁在一起的驅動程序,並不需要手動安裝。

以下片段顯示如何使用VCAP_SERVICES提供的連接詳細信息通過SSL連接到SQLDB。

 
public class SSLTEST { 
/** 
* @param args 
*/ 
public static void main(String[] args) { 
     String ServerName = "hostname or IP address"; 
     int PortNumber = 50001; 
     String DatabaseName = "SQLDB"; 
     String user = "your_user_id_from_VCAP_SERVICES"; 
     String userPassword = "your_password_from_VCAP_SERVICES";

java.util.Properties properties = new java.util.Properties(); properties.put("user", "user ID that has access to SQLDB"); properties.put("password", "password for the user ID that has access to SQLDB"); properties.put("sslConnection", "true"); String url = "jdbc:db2://" + ServerName + ":"+ PortNumber + "/" + DatabaseName + ":" + traceFileLocation + ";"; java.sql.Connection con = null; try { Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance(); } catch (Exception e) { System.out.println("Error: failed to load Db2 jcc driver."); } try { System.out.println("url: " + url); con = java.sql.DriverManager.getConnection(url, properties); if (con != null) { System.out.println("Success"); } else { System.out.println("Failed to make the connection"); } con.close(); } catch (Exception e) { if (con != null) { try { con.close(); } catch (Exception e2) { e2.printStackTrace(); } } e.printStackTrace(); } }

0

最後我使用的數據源連接到數據庫的名稱。 上下文ic = new InitialContext(); DataSource db =(DataSource)context.lookup(「jdbc/MyDatabase」);