顯示具有 Oracle 標籤的文章。 顯示所有文章
顯示具有 Oracle 標籤的文章。 顯示所有文章

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."); }
  }
}

1月 03, 2024

在 Oracle Cloud 上安裝 Alpine Linux

1. 建立一個以 Ubuntu 為作業系統的虛擬機(當作空殼)

2. 到 Alpine Linux 官網下載 VIRTUAL 版本的映像檔。例如 alpine-virt-3.19.0-x86_64.iso

3. 刷入映像檔

# sudo dd if=alpine-virt-3.19.0-x86_64.iso of=/dev/sda

4. 重新開機

5. 使用 Oracle Cloud 主控台連線(console)操作,進行安裝前準備

# mkdir /media/setup
# cp -a /media/sda/* /media/setup
# mkdir /lib/setup
# cp -a /.modloop/* /lib/setup
# /etc/init.d/modloop stop
# umount /dev/sda
# mv /media/setup/* /media/sda/
# mv /lib/setup/* /.modloop/
6. 循原本方式進行系統安裝(setup-alpine),網路介面直接用 eth0(dhcp)。安裝後驚人的空間使用(僅150MB)

1月 01, 2024

在 Oracle Cloud 建立首個虛擬主機

Oracle Cloud 資安要求嚴謹,首次註冊即強制要求啟動雙因子驗證。每次登入除了帳號密碼外,皆需搭配特定手機軟體(Oracle Mobile Authenticator)方能進入主控台。

主控台最基礎操作就從建立虛擬機(VM compute instance)開始,節點會以用戶的家鄉區(Home Region)作為預設值。基本上 Always Free 方案能選的項目不多,處理器部份固定是 E2.micro 然後作業系統有 Oracle Linux,Ubuntu, CentOS 等。

12月 27, 2023

Oracle 雲端免費資源(Cloud Always Free)

Oracle Cloud 相較於 Google Cloud Platform(GCP) 除了同樣提供免費運算資源外,機房區域多了東京可以選擇,對於亞太區傳輸延遲顯得更有優勢。另外 Oracle Cloud 登入強制啟用 2FA(Oracle Mobile Authenticator) 認證!

The Home Region(家鄉區)
When you sign up for Oracle Cloud Infrastructure, Oracle creates a tenancy for you in one region. This is your home region. Your home region is where your IAM resources are defined. Your home region contains your account information and identity resources.It is not changeable after your tenancy is provisioned. (區域列表)
Always Free Resources
All Oracle Cloud Infrastructure accounts (whether free or paid) have a set of resources that are free of charge in the home region of the tenancy, for the life of the account. These resources display the Always Free label in the Console (for Ampere A1 Compute shapes, see Compute). (圖例)
Compute(免費運算節點只能在家鄉區建立!)
All tenancies get a set of Always Free resources in the Compute service for creating compute virtual machine (VM) instances. You must create the Always Free compute instances in your home region.
  • Micro instances (AMD processor): All tenancies get up to two Always Free VM instances using the VM.Standard.E2.1.Micro shape, which has an AMD processor.(節點規格, 流量計價)
  • Ampere A1 Compute instances (Arm processor): All tenancies get the first 3,000 OCPU hours and 18,000 GB hours per month for free for VM instances using the VM.Standard.A1.Flex shape, which has an Arm processor.
Idle Compute Instances(閒置的節點會被收回)
Idle Always Free compute instances may be reclaimed by Oracle. Oracle will deem virtual machine and bare metal compute instances as idle if, during a 7-day period, the following are true:
  • CPU utilization for the 95th percentile is less than 20%
  • Network utilization is less than 20%
  • Memory utilization is less than 20% (applies to A1 shapes only)

9月 20, 2014

透過 PHP 連線 Oracle 資料庫

先談比較容易處理的 PHP 語法


在 Oracle 資料庫系統中,連線方式有兩種區別:Service Name 與 SID,不要弄錯了。手上的開發環境以 Service Name 為例。
  • 語法範例 (Oracle 11g 資料庫):
  • $db_id = "ORACLE-USER";
    $db_pwd = "ORACLE-PASSWORD";
    $oracle_db = "(DESCRIPTION = (ADDRESS_LIST = 
      (ADDRESS = (PROTOCOL = TCP)(HOST=10.1.1.1)(PORT=1521) ) )
      (CONNECT_DATA = (SERVICE_NAME=LODA) ) )";
    
    /* Go, Using UTF-8 Encoding */
    $conn = oci_connect($db_id, $db_pwd, $oracle_db, 'utf8');  
    $sql = "SELECT X,Y,Z FROM TABLE";
    
    if( !$conn ) { print_r (oci_error()); /* ErrCode */ }
    else
    {
     try
     {
      $stid=oci_parse($conn, $sql);
      oci_execute($stid);  /* Do Query */
      while( $row = oci_fetch_array($stid, OCI_BOTH) )
      { 
       $X = $row['X']; /* Fetch result, encoding to BIG5 */ 
       $Y_big5 = mb_convert_encoding ($row['Y'],"big5","utf-8");
      }
     }
     catch (Exception $err) { echo $err->getMessage(); }
    }
    /* Connection release */
    if($stid){ oci_free_statement($stid); }
    if($conn){ oci_close($conn); }
    
  • 指令不難,但在編碼的地方卡了一下,因為 Client 端只收 Big5 編碼。後來翻到函式 mb_convert_encoding($str, newEncode, oriEnconde) 用來轉換,所以順利解決。

再來是卡關好幾次的環境設定


因為在 Windows 環境下使用了 Uniform Server 作為開發平臺,原以為只要在控制面板內啟用 php_oci8.dll 與 php_pdo_oci.dll 兩項延伸模組就大公告成,沒想到整臺炸掉了!關於連線 Oracle 資料庫所需的函式套件:
  • 取得 Oracle Instant Client Package (例:instantclient-basic-nt-11.2.0.3.0.zip)
  • 解壓縮後將:oci.dll、ociw32.dll、orannzsbb11.dll、oraociei11.dll 丟到 C:\Windows\System32 目錄下
  • 啟用 php_oci8_11g.dll 與 php_pdo_oci.dll 兩項延伸模組
  • 重新啟動 Apache 應該沒問題了

最後是 PHP-CLI 環境參數


透過瀏覽器檢索,資料可從 Oracle 中讀出並在網頁中顯示。但此次開發最終要丟進排程執行,所以直覺把 PHP script 餵給 PHP-CLI(即php.exe) 處理應該就行了...。沒想到 PHP-CLI 使用另組環境參數運作(炸),暗雷何其多。舉凡任何 oci_* 語法均是未定義:
Fatal error: Call to undefined function oci_connect()
查詢 PHP-CLI 使用的環境參數並進行修正(此例為 php-cli.ini):
C:\UniServerZ\core\php54>php --ini
Configuration File (php.ini) Path: C:\Windows
Loaded Configuration File:         C:\UniServerZ\core\php54\php-cli.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)
這邊很明顯,只要在設定內把 extension 補上去就沒問題了。

6月 26, 2013

透過 JDBC 連線 Oracle 資料庫

要透過 Java JDBC 連線至 Oracle 資料庫,有幾個要注意的地方:

首先搞清楚連線對象是 "SID" 或 "Service Name" 因為兩者使用語法並不相同,其中:

1. SID (unique name of the INSTANCE)
jdbc:oracle:thin:[USER/PASSWORD]@[HOST][:PORT]:SID
2. Service Name (Alias to an INSTANCE)
jdbc:oracle:thin:[USER/PASSWORD]@//[HOST][:PORT]/SERVICE
實際例子:
Connection conn = null;
conn = DriverManager.getConnection
       ("jdbc:oracle:thin:ID/PASS//HOST_IP:1521/SERVICE_NAME"); 
再來,包裝你想送出的查詢
String StrX = "SELECT * FROM FOO";
sqlMsg = sqlMsg + "WHERE BAR=15";

Statement myQuery = conn.createStatement();
ResultSet Output = myQuery.executeQuery(sqlMsg);

while( Output.next() ) /* 透過迴圈取得資料 */
{
  System.out.println ( 
    Output.getString(1) + "," + Output.getString(2)+ "," +
    Output.getString(3) + "," + Output.getString(4)
  );
}

Output.close();
myQuery.close();
conn.close();
最後必須有一段程式碼,來處理例外狀況 (Java編譯時會偵測)
catch (ClassNotFoundException e) 
{ 
  System.err.println(e.getMessage()); 
}
catch (SQLException e) 
{ 
  System.err.println(e.getMessage()); 
} 
finally 
{ 
  try 
  { 
    if(conn != null) 
      conn.close(); 
  } 
  catch(SQLException e) 
  { 
    System.err.println(e); 
  } 
} 
--

有關 Java 8 中 java.sql.* 函式庫的變革:
The JDBC 4.2 API includes both the java.sql package, referred to as the JDBC core API, and the javax.sql package, referred to as the JDBC Optional Package API. This complete JDBC API is included in the Java Standard Edition (Java SE), version 7.

Since 1.8 -- new in the JDBC 4.2 API and part of the Java SE platform, version 8
Since 1.7 -- new in the JDBC 4.1 API and part of the Java SE platform, version 7

然後最重要的是從 JDBC 4.0 起,不需透過 Class.forName() 預先註冊 Driver
auto java.sql.Driver discovery - no longer need to load a java.sql.Driver class via Class.forName
編譯與執行 (工作目錄 c:\project)
> 編譯 javac foo.java
> 執行 java -cp "c:\project;c:\project\ojdbc8\ojdbc8.jar" foo