DBCP(DataBase Connection Pool)是由apace提供的數據庫連接池組件。
使用過程如下:
1.導入相關的包,注意dbcp2和dbcp1對jdk版本要求是不一樣的。除此之外還需要comms-logging包和commons-pool2包,這些包都可以在Apache官網下載。同時mysql-connector包版本要在5.0以上,否則使用時會報錯。
comms組件下載地址:http://commons.apache.org/proper/
2.創建配置文件dbcp.properties
#基本的設置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/demo01
username=root
password=123456
#初始化時連接池中connection數量
initialSize=10
#最大連接數量
maxActive=50
#最大的空閑連接數量
maxIdle=20
#最小的空閑鏈接數量
minIdle=5
#最大的等待時間,單位是毫秒
maxWait=60000
#建立連接時的附加參數,如果指定的編碼不一致數據庫中會出現亂碼
connectionProperties=useUnicode=true;characterEncoding=utf8
#是否開啟自動提交,跟事務的控制有關
defaultAutoCommit=true
#指定由連接池所創建的連接的事務隔離級別(TransactionIsolation)。
defaultTransactionIsolation=REPEATABLE_READ
3.編寫代碼
public class demo03 {
public static void main(String args[]){
InputStream in = demo03.class.getClassLoader().getResourceAsStream("dbcp.properties");
Properties pro = new Properties();
BasicDataSource bs = null;
try {
pro.load(in);
bs = BasicDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
Connection conn = bs.getConnection();
Statement stm = conn.createStatement();
int res = stm.executeUpdate("UPDATE `user` SET `name`='真的不知道'");
System.out.println(res);
conn.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
4.查看控制台輸出結果,更新了25條記錄
