1. 程式人生 > 其它 >Java文件閱讀筆記-C3P0連線池的使用

Java文件閱讀筆記-C3P0連線池的使用

技術標籤:文件閱讀筆記JavajavajdbcC3P0

這篇博文如何在應用程式中使用和配置C3P0

prom.xml如下:

<dependency>
  <groupId>com.mchange</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.5.5</version>
</dependency>

資料庫使用MySQL,這個例子連線knpcode庫,並且檢索EMPLOYEE表,這個EMPOLYEE表包含的域有ID,FIREST_NAME,LAST_NAME以及DEPARTMENT。

通過例項化ComboPooledDataSource類來建立C3P0連線池。

下面是一些資料庫相關的配置:

acquireIncrement:如果連線池中的連線被使用殆盡,將會以多少的數量進行增加,預設值為3。

initialPoolSize:程式啟動時連線池的數量,預設為3。

maxPoolSize:最大連線數,預設為15.

maxIdleTime:幾秒未使用的連線就會被丟棄,預設為0,不丟棄。

minPoolSize:連線池中最小的數量。

資料庫和連結池相關的配置都在db.properties檔案中:

DB.DRIVER_CLASS=com.mysql.cj.jdbc.Driver
DB.DB_URL=jdbc:mysql://localhost:3306/knpcode
DB.DB_USER=root
DB.DB_PASSWORD=admin
DB.INITIAL_POOL_SIZE=5
DB.MAX_POOL_SIZE=5

下面是建立ComboPooledDataSource相關的程式碼:

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DSCreator {
  private static ComboPooledDataSource pooledDS;
  static {
    try {
    	pooledDS = new ComboPooledDataSource();
      Properties properties = new Properties();
      // Loading properties file from classpath
      InputStream inputStream = DSCreator.class
                                         .getClassLoader()
                                         .getResourceAsStream("db.properties");
      if(inputStream == null){
        throw new IOException("File not found");
      }
      properties.load(inputStream);	
      pooledDS.setDriverClass(properties.getProperty("DB.DRIVER_CLASS"));
      pooledDS.setJdbcUrl(properties.getProperty("DB.DB_URL"));
      pooledDS.setUser(properties.getProperty("DB.DB_USER"));
      pooledDS.setPassword(properties.getProperty("DB.DB_PASSWORD"));

      pooledDS.setInitialPoolSize(Integer.parseInt(properties.getProperty("DB.INITIAL_POOL_SIZE")));
      // Default anyway
      pooledDS.setAcquireIncrement(3);
      pooledDS.setMaxPoolSize(Integer.parseInt(properties.getProperty("DB.MAX_POOL_SIZE")));
    }catch(IOException | PropertyVetoException e) {
      e.printStackTrace();
    }
  }
  public static DataSource getDataSource() {
    return pooledDS;
  } 
}

Test類用於建立連線以及獲取DataSource物件以及查詢資料庫:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;

public class DSDemo {
  public static void main(String[] args) {
    DSDemo dsDemo = new DSDemo();
    dsDemo.displayEmployeeById(16);
  }
  private void displayEmployeeById(int id){
    Connection connection = null; 
    String selectSQL = "SELECT * FROM EMPLOYEE WHERE id = ?";
    PreparedStatement prepStmt = null;
    try {
      DataSource ds = DSCreator.getDataSource();
      connection = ds.getConnection();
      prepStmt = connection.prepareStatement(selectSQL);
      prepStmt.setInt(1, id);
      ResultSet rs = prepStmt.executeQuery();
      while(rs.next()){
        System.out.println("id: " + rs.getInt("id"));
        System.out.println("First Name: " + rs.getString("FIRST_NAME"));
        System.out.println("Last Name: " + rs.getString("LAST_NAME"));
        System.out.println("Department: " + rs.getString("DEPARTMENT"));
      }
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      if(connection != null){
        try {
          connection.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}