12月 26, 2024

Java 透過 Oracle Wallet 連線資料庫

1. 需要準備 Oracle JDBC Drivers full版 (Wallet會用到oraclepki.jar等套件)

2. 編譯方式
D:\jdk17\bin\javac.exe -cp .;D:\ojdbc17-full\ojdbc17.jar OraDBConn.java
D:\jdk17\bin\java.exe  -cp .;D:\ojdbc17-full\ojdbc17.jar OraDBConn
3. 範例程式碼 (OraDBConn.java)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;

public class OraDBConn {
  public static void main(String[] args) {
    // Database connection information
    String host = "10.18.1.1";
    String port = "1522";
    String serviceName = "SNAME";
    String db_user_id  = "TESTID";
    String db_user_pwd = "2wsx3edc";
    String jdbcUrl = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=" +
                     "(PROTOCOL=TCPS)(HOST=" + host + ")(PORT=" + port + ")))" + 
                     "(CONNECT_DATA=(SERVICE_NAME=" + serviceName + ")))";    
    // Need [cwallet.sso] file for SSO authentication
    System.setProperty("oracle.net.wallet_location", "D:\\wallet");    
    try 
    {
      // Establish a connection using the Oracle Wallet
      Connection connection = 
        DriverManager.getConnection(jdbcUrl, db_user_id, db_user_pwd);     
      System.out.println("Connection established successfully!");
      
      Statement stmt    = connection.createStatement();
      String    sqlcode = "SELECT * FROM OWNER.Table13 WHERE ROWNUM <= 3";
      ResultSet rs      = stmt.executeQuery(sqlcode);           
      while(rs.next())  System.out.println(rs.getString(5) + "\t");
      
      connection.close();
    } 
    catch (SQLException e) { 
      e.printStackTrace(); System.out.println("Failed connect."); }
  }
}

沒有留言:

張貼留言