Java訪問SSL enabled DB2 Database

zchbaby2000發表於2018-03-23

 生成JAVA JKS證照檔案,為JDBC準備,這裡的密碼是對檔案進行加密的密碼,自己可以隨意設定的,這裡設定為hell0man
這裡不一定要在DB2 Server上生成證照檔案,隨便一個能執行Java的地方都可以
這裡的mydbserver.arm是從DB2 Server上取下來的

$ keytool -import -trustcacerts -file "mydbserver.arm" -keystore "mynewdbclient.jks"


Sample Java code
===================================================================
public class SSLTest
{
public static void main (String[] args)
{
  String ServerName = "192.168.110.10";
  int PortNumber = 50001;
  String DatabaseName = "TEST";
  java.util.Properties properties = new java.util.Properties();
     
  properties.put("user", "db2inst1");  --> 訪問資料庫的使用者名稱
  properties.put("password", "passw0rd"); --> 訪問資料庫的密碼
  properties.put("sslConnection", "true");
  System.setProperty("javax.net.ssl.trustStore", "C:\\temp\\ssl_client\\mynewdbclient.jks");  
  System.setProperty("javax.net.ssl.trustStorePassword", "hell0man");
   
  String url = "jdbc:db2://" + ServerName + ":"+ PortNumber + "/" + DatabaseName+ ":traceFile=foobar.txt;traceLevel="+ 0xFFFFFFFF+ ";";
                 
  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);
      java.sql.Statement s2 = con.createStatement();
    
       try
       {
            s2.executeUpdate("drop table t1");
       }
       catch(Exception e)
       {
            System.out.println("drop is failing");
       }
        
       try
       {
            s2.executeUpdate ("create table t1 (c1 int)");
       }
       catch(Exception e)
       {
            System.out.println("create is failing");
       }
        
       String str = "insert into t1 values (100)";
       s2.executeUpdate(str);
        
       java.sql.PreparedStatement ps = con.prepareStatement ("select * from t1");
       java.sql.ResultSet rs = ps.executeQuery ();
        
       while(rs.next())
       {
            System.out.println(rs.getString(1));
       }
        
      con.close();
   }
   catch (Exception e)
   {
      e.printStackTrace();
   }
 }
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/725820/viewspace-2152189/,如需轉載,請註明出處,否則將追究法律責任。

相關文章