全部產品
Search
文件中心

ApsaraDB for OceanBase:C3P0 串連池串連 OceanBase 資料庫樣本程式

更新時間:Jul 23, 2024

本文將介紹如何使用 C3P0 串連池、MySQL Connector/J 和 OceanBase 資料庫構建一個應用程式,實現基本的資料庫操作,包括建立表、插入、刪除、更新和查詢資料等。

image.png點擊下載 c3p0-mysql-jdbc 樣本工程

前提條件

  • 您已安裝 OceanBase 資料庫並且建立了 MySQL 模式租戶。

  • 您已安裝 JDK 1.8 和 Maven。

  • 您已安裝 Eclipse。

    說明

    本文檔運行代碼使用的工具是 Eclipse IDE for Java Developers 2022-03 版本,您也可以根據個人喜好選擇適合自己的工具啟動並執行範例程式碼。

操作步驟

說明

本文中給出的操作步驟是在 Windows 環境下使用 Eclipse IDE for Java Developers 2022-03 編譯和運行該專案的步驟。如果您使用的是其他動作系統內容或編譯器,那麼操作步驟可能會略有不同。

  1. c3p0-mysql-jdbc專案匯入到 Eclipse 中。

  2. 擷取 OceanBase 資料庫 URL。

  3. 修改c3p0-mysql-jdbc專案中的資料庫連接資訊。

  4. 運行c3p0-mysql-jdbc專案。

步驟一:將 c3p0-mysql-jdbc 專案匯入到 Eclipse 中

  1. 開啟 Eclipse,在功能表列上選擇 File->Open Projects from File System

  2. 在彈出的對話方塊中,點擊 Directory 按鈕選擇專案所在的目錄,然後點擊 Finish 完成匯入。

    說明

    當使用 Eclipse 匯入 Maven 專案時,Eclipse 會自動檢測專案中的pom.xml檔案,並根據檔案中描述的依賴關係自動下載所需的依賴庫,並將它們添加到專案中。

    image.png

  3. 查看專案情況。

    image.png

步驟二:擷取 OceanBase 資料庫 URL

  1. 聯絡 OceanBase 資料庫部署人員或者管理員擷取相應的資料庫連接串。

    樣本如下:

    obclient -hxxx.xxx.xxx.xxx -P3306 -utest_user001 -p****** -Dtest

    更多串連串的資訊,請參見 擷取串連參數

  2. 根據 OceanBase 資料庫連接串資訊填寫下面 URL 的對應資訊。

    jdbc:mysql://$host:$port/$database_name?user=$user_name&password=$password

    參數說明:

    • $hostOceanBase 資料庫連接的網域名稱。

    • $port:OceanBase 資料庫連接連接埠,MySQL 模式租戶預設是 3306。

    • $database_name:需要訪問的資料庫名稱。

    • $user_name:租戶的串連帳號。

    • $password:提供賬戶密碼。

    更多有關 MySQL Connector/J 串連屬性資訊,請參見 Configuration Properties

    樣本如下:

    jdbc:mysql://xxx.xxx.xxx.xxx:3306/test?user=test_user001&password=******

步驟三:修改 c3p0-mysql-jdbc 專案中的資料庫連接資訊

根據 步驟二:擷取 OceanBase 資料庫 URL 中擷取的資訊修改檔案c3p0-mysql-jdbc/src/main/resources/c3p0-config.xml中的資料庫連接資訊。

樣本如下:

  • OBServer 節點的 IP 位址為xxx.xxx.xxx.xxx

  • 訪問連接埠使用的是 3306。

  • 需要訪問的資料庫名稱為test

  • 租戶的串連賬戶是test_user001

  • 密碼是******

代碼如下:

...
        <property name="jdbcUrl">jdbc:mysql://xxx.xxx.xxx.xxx:3306/test</property>
        <property name="user">test_user001</property>
        <property name="password">******</property>
...

步驟四:運行 c3p0-mysql-jdbc 專案

  1. 在專案導航器視圖中,找到並展開 src/main/java 目錄。

  2. 右鍵點擊 Main.java 檔案,然後選擇 Run As->Java Application

    image.png

  3. 在 Eclipse 的控制台視窗中來查看專案的日誌資訊和輸出結果。

    image.png

  4. 也可以在 OceanBase 用戶端(OBClient)中執行以下 SQL 陳述式查看結果。

    obclient [test]> SELECT * FROM test_c3p0;

    返回結果如下:

    +------+--------------+
    | id   | name         |
    +------+--------------+
    |    5 | test_update  |
    |    6 | test_insert6 |
    |    7 | test_insert7 |
    |    8 | test_insert8 |
    |    9 | test_insert9 |
    +------+--------------+
    5 rows in set

專案代碼介紹

點擊 c3p0-mysql-jdbc 下載專案代碼,是一個名稱為c3p0-mysql-jdbc.zip的壓縮包。

解壓後,得到一個名為c3p0-mysql-jdbc的檔案夾。目錄結構如下所示:

c3p0-mysql-jdbc
├── src
│   └── main
│       ├── java
│       │   └── com
│       │        └── example
│       │           └── Main.java
│       └── resources
│           └── c3p0-config.xml 
└── pom.xml

檔案說明:

  • src:原始碼根目錄。

  • main:主代碼目錄,包含應用程式的主要邏輯。

  • java:Java 原始碼目錄。

  • com:Java 包目錄。

  • example:樣本專案的包目錄。

  • Main.java:主類,包含建立表和插入資料等邏輯。

  • resources:資源檔目錄,包含設定檔等。

  • c3p0-config.xml:C3P0 串連池的設定檔。

  • pom.xml:Maven 專案的設定檔,用於管理專案的依賴和構建設定。

pom.xml 代碼介紹

pom.xml檔案是 Maven 專案的設定檔,定義了專案的依賴項、外掛程式和構建規則等資訊。Maven 是一個 Java 專案管理工具,可以自動下載依賴項、編譯和打包專案等操作。

本文pom.xml檔案的代碼主要包括以下幾個部分:

  1. 檔案聲明語句。

    聲明本檔案是一個 XML 檔案,使用的 XML 版本是1.0,字元編碼方式是UTF-8

    代碼如下:

    <?xml version="1.0" encoding="UTF-8"?>
  2. 配置 POM 的命名空間和 POM 模型版本。

    1. 通過xmlns指定 POM 的命名空間為http://maven.apache.org/POM/4.0.0

    2. 通過xmlns:xsi指定 XML 命名空間http://www.w3.org/2001/XMLSchema-instance

    3. 通過xsi:schemaLocation指定 POM 的命名空間為http://maven.apache.org/POM/4.0.0和 POM 的 XSD 檔案的位置為http://maven.apache.org/xsd/maven-4.0.0.xsd

    4. 通過<modelVersion>元素指定了該 POM 檔案使用的 POM 模型版本為4.0.0

    代碼如下:

    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
     <!-- 其他配置 -->
    
    </project>
  3. 配置基本資料。

    1. 通過<groupId>指定專案所屬組織為com.example

    2. 通過<artifactId>指定專案的名稱為testc3p0

    3. 通過<version>專案的版本號碼為1.0-SNAPSHOT

    代碼如下:

        <groupId>com.example</groupId>
        <artifactId>testc3p0</artifactId>
        <version>1.0-SNAPSHOT</version>
  4. 設定項目源檔案的屬性。

    指定 Maven 的編譯器外掛程式為maven-compiler-plugin,並設定了原始碼和目標 Java 版本都為 8。這意味著專案的原始碼使用 Java 8 特性編寫,且編譯後的位元組碼也將相容 Java 8 運行時環境。這樣設定可以確保專案在編譯和運行時能夠正確地處理 Java 8 的文法和特性。

    說明

    Java 1.8 和 Java 8 是同一個版本的不同命名方式。

    代碼如下:

        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>8</source>
                        <target>8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
  5. 設定項目所相依元件。

    說明

    本部分代碼定義專案所相依元件是 MySQL Connector/J 的 8.0.25 版本,如果需要瞭解其他版本的資訊,請參見MySQL Connector/J

    通過<dependency>定義依賴項:

    • 添加mysql-connector-java依賴庫:

    1. 通過<groupId>指定依賴項所屬的組織為mysql

    2. 通過<artifactId>指定依賴項的名稱為mysql-connector-java

    3. 通過<version>指定依賴項的版本號碼為8.0.25

    • 添加c3p0依賴庫:

    1. 通過<groupId>指定依賴項所屬的組織為com.mchange

    2. 通過<artifactId>指定依賴項的名稱為c3p0

    3. 通過<version>指定依賴項的版本號碼為0.9.5.5

    代碼如下:

        <dependencies>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.25</version>
            </dependency>
            <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.5.5</version>
            </dependency>
        </dependencies>

c3p0-config.xml 代碼介紹

c3p0-config.xml檔案是 C3P0 串連池設定檔,用於配置與資料庫的串連相關的屬性。通過設定各個<property>元素的值,可以設定資料庫驅動、串連 URL、使用者名稱、密碼、串連池大小等屬性。

本文c3p0-config.xml檔案的代碼主要包括以下幾個部分:

  1. 檔案聲明語句。

    聲明本檔案是一個 XML 檔案,使用的 XML 版本是1.0,字元編碼方式是UTF-8

    代碼如下:

    <?xml version="1.0" encoding="UTF-8"?>
  2. 配置基本資料。

    1. 通過<c3p0-config>包含 c3p0 串連池的配置資訊。

    2. 通過<named-config name="oceanbase">定義了一個具名配置,名稱為oceanbase。在代碼中,可以使用這個名稱來引用該具名配置,並擷取與oceanbase資料庫相關的串連資訊和串連池屬性。

    代碼如下:

    <c3p0-config>
        <named-config name="oceanbase">
    
            // 配置各個 <property> 元素的值
    
        </named-config>
    </c3p0-config>
  3. 設定資料庫驅動。

    通過<property>用於指定串連 OceanBase 資料庫時使用的 MySQL JDBC 驅動程式的類名為com.mysql.cj.jdbc.Driver

    說明

    有關 MySQL Connector/J 實作類別的名稱資訊,請參見 Driver/Datasource Class Name

    代碼如下:

            <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
  4. 設定資料庫串連資訊。

    1. 設定資料庫連接的 URL,包括主機 IP、連接埠號碼、需要訪問的資料庫和 URL 參數等資訊。

    2. 設定資料庫使用者名稱。

    3. 設定資料庫密碼。

    代碼如下:

            <property name="jdbcUrl">jdbc:mysql://$host:$port/$database_name</property>
            <property name="user">$user_name</property>
            <property name="password">$password</property>

    參數解釋:

    • $hostOceanBase 資料庫連接的網域名稱。

    • $port:OceanBase 資料庫連接連接埠,MySQL 模式租戶預設是 3306。

    • $database_name:需要訪問的資料庫名稱。

    • $user_name:租戶的串連帳號。

    • $password:提供賬戶密碼。

  5. 配置其他 c3p0 資料庫連接池的配置項。

    1. 設定串連池在需要時一次性增加的串連數為 20。即在串連池中的串連不足時,每次增加串連的數量為 20。

    2. 設定串連池的初始大小為 10。即串連池在啟動時會預先建立 10 個串連。

    3. 設定串連池的最小串連數為 5。即串連池中保持的最少串連數量不低於 5。

    4. 設定串連池的最大串連數為 30。即串連池中允許的最大串連數量不超過 30。

    5. 設定每個串連的最大緩衝語句數量為 0。即不緩衝語句。

    6. 設定每個串連在串連池中的最大緩衝語句數量為 0。即每個串連不緩衝語句。

    7. 設定 c3p0 使用的輔助線程數量為 3。這些輔助線程用於執行慢速 JDBC 操作。

    8. 設定 c3p0 串連的屬性檢查周期為 3 秒。即每隔 3 秒檢查一次串連的屬性。

    9. 設定擷取串連的逾時時間為 1000 毫秒。即如果在 1000 毫秒內無法擷取到串連,則拋出逾時異常。

    10. 設定串連池中空閑串連的檢查周期為 3 秒。即每隔 3 秒檢查一次空閑串連的狀態。

    11. 設定串連池中串連的最大空閑時間為 10 秒。即如果串連在 10 秒內沒有被使用,則會被關閉。

    12. 設定串連池中超出最大串連數的串連的最大空閑時間為 5 秒。即如果串連超過最大串連數且處於空閑狀態超過 5 秒,則會被關閉。

    13. 設定嘗試擷取串連時的重試延遲時間為 1000 毫秒。即如果擷取串連失敗,將在 1000 毫秒後再次嘗試。

    14. 設定 c3p0 的自動化的測試表為Test。這是一個用於測試連接是否有效特殊表。

    15. 設定在歸還串連到串連池時是否測試連接的有效性。如果設定為 true,則在串連歸還到串連池時會進行串連有效性測試。

    代碼如下:

           <property name="acquireIncrement">20</property>
           <property name="initialPoolSize">10</property>
           <property name="minPoolSize">5</property>
           <property name="maxPoolSize">30</property>
           <property name="maxStatements">0</property>
           <property name="maxStatementsPerConnection">0</property>
           <property name="numHelperThreads">3</property>
           <property name="propertyCycle">3</property>
           <property name="checkoutTimeout">1000</property>
           <property name="idleConnectionTestPeriod">3</property>
           <property name="maxIdleTime">10</property>
           <property name="maxIdleTimeExcessConnections">5</property>
           <property name="acquireRetryDelay">1000</property>
           <property name="automaticTestTable">Test</property>
           <property name="testConnectionOnCheckin">true</property>
重要

具體的屬性(參數)配置取決於專案需求和資料庫的特點,建議您根據實際情況進行調整和配置。更多 C3P0 串連池配置參數資訊,請參見C3P0

C3P0 串連池常用配置項:

分類

屬性

預設值

描述

必選項

driverClass

N/A

驅動類名

jdbcUrl

N/A

用於指定資料庫的串連 URL。

user

N/A

用於指定串連資料庫時使用的使用者名稱。

password

N/A

用於指定串連資料庫時使用的密碼。

基本配置

acquireIncrement

3

用於設定在串連池中需要時一次性擷取的串連數。例如,如果acquireIncrement的值為 20,而串連池中當前只有 5 個空閑串連,則在擷取串連時,串連池會一次性建立 20 個新串連,以滿足應用程式的需求。

acquireRetryAttempts

30

用於設定從資料庫擷取新串連失敗後的重試次數。如果這個值小於或等於零,C3P0 將繼續嘗試無限地擷取一個串連。

maxIdleTime

0

用於設定串連在串連池中的最大空閑時間,0 表示空閑串連永遠不會到期。例如,如果將maxIdleTime設定為 10 秒,則串連池中的串連在空閑時間超過 10 秒後,若沒有被使用,將被串連池關閉並移除。下次應用程式再次請求串連時,串連池會重新建立一個新的串連。

maxPoolSize

15

用於設定串連池中的最大串連數。當串連池中的串連數達到maxPoolSize指定的值時,新的串連請求將被阻塞,直到有串連被釋放回串連池。

MinPoolSize

3

用於設定串連池中的最小串連數。即使在串連不被使用時,串連池也會保持至少minPoolSize指定的數量的串連。

initialPoolSize

3

用於設定串連池在啟動時預先建立的串連數量,取值應在minPoolSizmaxPoolSize之間。即在串連池初始化時,會建立initialPoolSize指定的數量的串連。

可選擇配置項

acquireRetryDelay

1000

用於設定在擷取串連時的重試延遲時間,單位毫秒。當應用程式從串連池擷取串連時,如果串連池中沒有可用的串連,可能會發生串連擷取失敗的情況。此時,串連池會根據acquireRetryDelay的配置進行重試。

autoCommitOnClose

false

用於設定在串連關閉時是否自動認可事務。預設值為false,即串連在關閉時不會自動認可事務。如果應用程式需要在串連關閉之前顯式地提交事務,可以將autoCommitOnClose設定為true

重要

自動認可事務可能會導致資料不一致或丟失的情況。因此,應在確保事務完整性的情況下謹慎使用autoCommitOnClose。在大多數情況下,建議手動管理事務,確保事務的提交或復原發生在適當的時機。

automaticTestTable

null

用於設定串連池的自動化的測試表。C3P0 將建立一個指定名稱的空表,並使用對該表的查詢來測試 Connection。預設值為null,表示不執行任何測試語句。例如,如果將automaticTestTable設定為Test,C3P0 將建立一張名為Test的空表,並使用其內建的查詢語句進行測試。

說明

如果在串連池中同時配置了automaticTestTablepreferredTestQuery,C3P0 會優先使用preferredTestQuery來執行測試查詢,而忽略automaticTestTable的設定。

idleConnectionTestPeriod

0

用於設定串連池執行空閑串連檢測的時間間隔,以毫秒為單位。即串連池會每隔一定的時間間隔對空閑串連進行一次測試。預設值是 0,表示不進行空閑串連檢測。

maxStatements

0

用於設定串連池的最大預先處理語句數量。

    說明

    如果maxStatementsmaxStatementsPerConnection都為 0,則不會啟用語句緩衝。

    如果maxStatements為 0,但maxStatementsPerConnection為非零值,則會啟用語句緩衝,但不會強制執行全域限制,只有每個串連的最大限制生效。

    maxStatements控制串連池中所有串連的緩衝語句的總數。如果設定了maxStatements,它應該是一個相當大的數量,因為每個串連池中的串連都需要自己獨立的、不同的緩衝語句集合。

maxStatementsPerConnection

0

用於設定每個串連中允許存在的最大預先處理語句數量。

    說明

    如果maxStatementsmaxStatementsPerConnection都為 0,則不會啟用語句緩衝。

    如果maxStatementsPerConnection為 0,但maxStatements為非零值,則會啟用語句緩衝,並強制執行全域限制,但對於單個串連不會設定緩衝語句的數量限制。

numHelperThreads

3

用於指定用於非同步處理任務的輔助線程的數量。

    說明

    輔助線程的數量越多,可以平行處理的任務就越多,從而提高串連池的處理能力和響應速度。

    設定過多的輔助線程可能會導致系統資源的過度消耗,因此應根據系統的硬體設定和效能測試來合理地設定numHelperThreads的值。

preferredTestQuery

null

定義所有串連測試都執行的測試語句。在使用串連測試的情況下這個一顯著提高測試速度。

重要

測試的表必須在初始資料來源的時候就存在。

checkoutTimeout

0

用於指定從串連池中擷取串連的逾時時間,單位毫秒。預設值為 0,表示沒有逾時限制。當串連池用完時用戶端調用getConnection()後等待擷取新串連的時間,逾時後將拋出SQLException

不建議配置項

breakAfterAcquireFailure

false

用於控制當串連擷取失敗時是否中斷串連池的擷取操作。擷取串連失敗將會引起所有等待串連池來擷取串連的線程拋出異常。但是資料來源仍有效保留,並在下次調用getConnection()的時候繼續嘗試擷取串連。

  • 如果設定為true,則在多次擷取串連失敗後,串連池將不再嘗試擷取串連,而是快速失敗並拋出異常。

  • 如果設定為false,串連池將繼續嘗試擷取串連,直到達到擷取串連的逾時時間。

testConnectionOnCheckout

false

用於指定在從串連池中擷取串連時是否對串連進行測試。

  • 如果設定為true,則在擷取串連時會執行串連測試。此特性要慎用,會造成至少多一倍的資料庫調用。

  • 如果設定為false,則不會執行串連測試。

說明

雖然執行串連測試可以確保串連是有效,但也會增加一定的額外開銷。因此,應根據具體的應用需求和效能要求來決定是否啟用串連測試。如果應用程式對串連的可用性要求較高,可以啟用串連測試。但如果串連池中的串連經常被頻繁地擷取和釋放,可能會導致串連測試過於頻繁,從而影響效能。

testConnectionOnCheckin

false

用於指定在將串連歸還到串連池時是否對串連進行測試。

  • 如果設定為true,則在歸還串連到串連池時會執行串連測試。此特性要慎用,同樣會造成至少多一倍的資料庫調用。

  • 如果設定為false,則不會執行串連測試。

說明

儘管執行串連測試可以確保串連是有效,但這也會增加一定的額外開銷。因此,應根據具體的應用需求和效能要求來決定是否啟用串連測試。如果應用程式對串連的可用性要求較高,可以啟用串連測試。但如果串連池中的串連被頻繁地擷取和歸還,可能會導致串連測試過於頻繁,從而影響效能。

Main.java 代碼介紹

Main.java檔案是樣本程式的一部分,用於示範通過 c3p0 串連池擷取資料庫連接,並在事務中執行一系列資料庫操作,包括建立表、插入資料、刪除資料、更新資料、查詢資料,並將查詢結果列印出來。它展示了如何使用 c3p0 串連池來管理資料庫串連和執行事務操作,以提高資料庫操作的效率和效能。

本文Main.java檔案的代碼主要包括以下幾個部分:

  1. 定義包和匯入java.sql的介面。

    1. 聲明當前代碼所屬的包名為com.example

    2. 匯入java.sql.Connection類,用於表示資料庫連接。

    3. 匯入java.sql.PreparedStatement類,用於執行先行編譯的資料庫操作。

    4. 匯入java.sql.ResultSet類,用於表示資料庫查詢結果集。

    5. 匯入com.mchange.v2.c3p0.ComboPooledDataSource類,用於使用 c3p0 串連池。

    代碼如下:

    package com.example;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import com.mchange.v2.c3p0.ComboPooledDataSource;
  2. 定義類名和方法。

    1. 定義一個名為Main的公用類,作為程式的進入點。類名需要與檔案名稱保持一致。

    2. 定義一個公用靜態方法main,作為程式的起始執行點。

    3. 使用try-with-resources語句,擷取一個資料庫連接和建立先行編譯的 SQL 陳述式。

    4. 資料庫事務操作。

    5. 捕獲可能發生的異常並列印異常堆棧資訊。

    6. 定義一個私人靜態方法getConnection,用於擷取 c3p0 串連池中的資料庫連接。在方法內部,首先建立一個ComboPooledDataSource對象cpds,該對象通過參數oceanbase指定了串連池的配置。然後,通過cpds.getConnection()方法從串連池中擷取一個資料庫連接,並將其返回。

    代碼如下:

    public class Main {
    
        public static void main(String[] args) {
            try (
                //擷取一個資料庫連接
                // 建立先行編譯的 SQL 陳述式
                ) {
    
                // 資料庫事務操作:開始事務、建立表、插入資料、刪除資料、更新資料、查詢資料和提交事務
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private static Connection getConnection() throws Exception {
            ComboPooledDataSource cpds = new ComboPooledDataSource("oceanbase");
            return cpds.getConnection();
        }
    }
  3. 擷取一個資料庫連接。

    擷取一個資料庫連接並將其賦值給conn變數。

    代碼如下:

                 Connection conn = getConnection();
  4. 建立先行編譯 SQL 陳述式。

    1. 建立一個用於建立名為test_c3p0的資料庫表的先行編譯 SQL 陳述式。

    2. 建立一個用於向test_c3p0表插入資料的先行編譯 SQL 陳述式。

    3. 建立一個用於從test_c3p0表中刪除資料的先行編譯 SQL 陳述式。

    4. 建立一個用於更新test_c3p0表中的資料的先行編譯 SQL 陳述式。

    5. 建立一個用於從test_c3p0表中查詢資料的先行編譯 SQL 陳述式。

    代碼如下:

                 PreparedStatement stmtCreate = conn.prepareStatement("CREATE TABLE test_c3p0 (id INT, name VARCHAR(32))");
                 PreparedStatement stmtInsert = conn.prepareStatement("INSERT INTO test_c3p0 VALUES (?, ?)");
                 PreparedStatement stmtDelete = conn.prepareStatement("DELETE FROM test_c3p0 WHERE id < ?");
                 PreparedStatement stmtUpdate = conn.prepareStatement("UPDATE test_c3p0 SET name = ? WHERE id = ?");
                 PreparedStatement stmtSelect = conn.prepareStatement("SELECT * FROM test_c3p0")
  5. 開始事務。

    設定資料庫連接的自動認可為false,從而啟用事務的機制。

    代碼如下:

                conn.setAutoCommit(false); 
  6. 建立表。

    執行建立表的 SQL 陳述式。

    代碼如下:

                stmtCreate.execute();
  7. 插入資料。

    使用for迴圈向test_c3p0表插入 10 條資料,第一列的值是變數i的值,第二列的值是字串test_insert後面加上變數i的值。

    代碼如下:

                for (int i = 0; i < 10; i++) {
                    stmtInsert.setInt(1, i);
                    stmtInsert.setString(2, "test_insert" + i);
                    stmtInsert.executeUpdate();
                }
  8. 刪除資料。

    設定刪除語句的參數為 5 並執行刪除操作。

    代碼如下:

                stmtDelete.setInt(1, 5);
                stmtDelete.executeUpdate();
  9. 更新資料。

    設定更新語句的第一個參數是test_update,第二個參數是 5 並執行更新操作。

    代碼如下:

                stmtUpdate.setString(1, "test_update");
                stmtUpdate.setInt(2, 5);
                stmtUpdate.executeUpdate();
  10. 查詢資料。

    1. 執行查詢語句,並將查詢結果儲存在ResultSet對象rs中。

    2. 使用 while 迴圈,通過 rs.next() 判斷結果集中是否還有下一行資料。如果有,則執行迴圈內的代碼。

    3. 迴圈內的代碼列印每一行資料的id列和name列的值。

    4. 關閉結果集,釋放相關資源。

    代碼如下:

                ResultSet rs = stmtSelect.executeQuery();
                while (rs.next()) {
                    System.out.println(rs.getInt("id") + "   " + rs.getString("name"));
                }
                rs.close();
  11. 提交事務。

    代碼如下:

                conn.commit(); 

完整的代碼展示

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.oceanbase</groupId>
    <artifactId>testc3p0</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version>
        </dependency>
    </dependencies>
</project>

c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <named-config name="oceanbase">
        <!-- Configure Database Driver -->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <!-- Configure Database Link Address -->
        <property name="jdbcUrl">jdbc:mysql://$host:$port/$database_name</property>
        <!-- Configure database username -->
        <property name="user">$user_name</property>
        <!-- Configure database password -->
        <property name="password">$password</property>
        <!-- How many connection objects does the database Connection pool want from the database at one time -->
        <property name="acquireIncrement">20</property>
        <!-- Initialize connections -->
        <property name="initialPoolSize">10</property>
        <!-- Minimum number of connections -->
        <property name="minPoolSize">5</property>
        <!-- The maximum number of connections reserved in the Connection pool. Default: 15 -->
        <property name="maxPoolSize">30</property>
        <!-- JDBC standard parameter used to control the number of PreparedStatements loaded within the data source. However, the pre cached statements belong to a single connection rather than the entire Connection pool. So setting this parameter requires considering multiple factors. If both maxStatements and maxStatementsPerConnection are 0, the cache is turned off. Default:0 -->
        <property name="maxStatements">0</property>
        <!-- MaxStatementsPerConnection defines the maximum number of cached statements owned by a single connection in the Connection pool. Default: 0 -->
        <property name="maxStatementsPerConnection">0</property>
        <!-- C3p0 is an asynchronous operation, and slow JDBC operations are completed by the helper process. Expanding these operations can effectively improve performance by enabling multiple operations to be executed simultaneously through multithreading. Default:3 -->
        <property name="numHelperThreads">3</property>
        <!-- The user can wait up to 300 seconds before modifying the system configuration parameters. Default: 300 -->
        <property name="propertyCycle">3</property>
        <!-- The default setting for obtaining the connection timeout is to wait for a unit of milliseconds -->
        <property name="checkoutTimeout">1000</property>
        <!-- Check all free connections in the Connection pool every few seconds. Default: 0 -->
        <property name="idleConnectionTestPeriod">3</property>
        <!-- The maximum idle time, within seconds, if not used, the connection will be discarded. If it is 0, it will never be discarded. Default: 0 -->
        <property name="maxIdleTime">10</property>
        <!-- Configure the lifetime of the connection. Connections beyond this time will be automatically disconnected and discarded by the Connection pool. Of course, the connection being used will not be immediately disconnected, but will wait for it to close before disconnecting. When configured to 0, there is no restriction on the lifetime of the connection. -->
        <property name="maxIdleTimeExcessConnections">5</property>
        <!-- The interval time between two connections, in milliseconds. Default: 1000 -->
        <property name="acquireRetryDelay">1000</property>
        <!-- C3p0 will create an empty table called Test and use its built-in query statement for testing. If this parameter is defined, the property preferredTestQuery will be ignored. You cannot perform any operations on this Test table, it will only be used for c3p0 testing. Default: null -->
        <property name="automaticTestTable">Test</property>
        <!-- Test if the connection is valid when obtaining it -->
        <property name="testConnectionOnCheckin">true</property>
    </named-config>
</c3p0-config>

Main.java

package com.example;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class Main {

    public static void main(String[] args) {
        try (Connection conn = getConnection();

             PreparedStatement stmtCreate = conn.prepareStatement("CREATE TABLE test_c3p0 (id INT, name VARCHAR(32))");
             PreparedStatement stmtInsert = conn.prepareStatement("INSERT INTO test_c3p0 VALUES (?, ?)");
             PreparedStatement stmtDelete = conn.prepareStatement("DELETE FROM test_c3p0 WHERE id < ?");
             PreparedStatement stmtUpdate = conn.prepareStatement("UPDATE test_c3p0 SET name = ? WHERE id = ?");
             PreparedStatement stmtSelect = conn.prepareStatement("SELECT * FROM test_c3p0")) {
            
            // Begin transaction
            conn.setAutoCommit(false); 

            // Create table
            stmtCreate.execute();

            // Insert data
            for (int i = 0; i < 10; i++) {
                stmtInsert.setInt(1, i);
                stmtInsert.setString(2, "test_insert" + i);
                stmtInsert.executeUpdate();
            }

            // Delete data
            stmtDelete.setInt(1, 5);
            stmtDelete.executeUpdate();

            // Update data
            stmtUpdate.setString(1, "test_update");
            stmtUpdate.setInt(2, 5);
            stmtUpdate.executeUpdate();

            // Query data
            ResultSet rs = stmtSelect.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getInt("id") + "   " + rs.getString("name"));
            }
            rs.close();
            
            // Commit transaction
            conn.commit(); 
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Connection getConnection() throws Exception {
        ComboPooledDataSource cpds = new ComboPooledDataSource("oceanbase");
        return cpds.getConnection();
    }
}

相關文檔

更多 MySQL Connector/J 的資訊,請參見 Overview of MySQL Connector/J