2015-09-04 120 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”);