數(shù)據(jù)庫(kù)連接池負(fù)責(zé)分配、管理和釋放數(shù)據(jù)庫(kù)連接,允許程序重復(fù)使用一個(gè)現(xiàn)有的數(shù)據(jù)庫(kù)連接,而不是重復(fù)新建立一個(gè)。
![Uploading 連接池_413693.png . . .]
建立連接池就是在原來(lái)創(chuàng)建jdbc的基礎(chǔ)上,把原先獲得的Connection接口對(duì)象保存到一個(gè)list數(shù)組中。避免重復(fù)連接。
自定義連接池:
package com.whd.utils;
import java.util.*;
import java.sql.*;
/**
* @author Administrator
*自定義連接池
*/
public class MyDbPool {
private static String path,url,name,pass;
//存儲(chǔ)當(dāng)前的連接對(duì)象
private static List<Connection> list;
static {
ResourceBundle rs = ResourceBundle.getBundle("dbinfo");
path = rs.getString("driverpath");
url = rs.getString("dburl");
name = rs.getString("username");
pass = rs.getString("pass");
//list = new ArrayList<Connection>();
list = Collections.synchronizedList(new ArrayList<>());
try {
//加載驅(qū)動(dòng)
Class.forName(path);
//創(chuàng)建5個(gè)連接對(duì)象
for(int i = 0;i < 5;i++){
list.add(DriverManager.getConnection(url,name,pass));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**獲取連接對(duì)象
* @return
*/
public static Connection getConn(){
if(list.size()>0){
return list.remove(0);
}else{
throw new RuntimeException("請(qǐng)先關(guān)閉連接對(duì)象!");
}
}
//銷毀連接對(duì)象,其實(shí)就是再次添加進(jìn)來(lái)
public static void destory(Connection conn){
list.add(list.size(), conn);
}
}
自定義jdbc工具類:
package com.whd.utils;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author Administrator
*封裝數(shù)據(jù)庫(kù)工具類
*/
public class MyDbutils {
//連接對(duì)象
private static Connection conn;
//獲取操作sql的語(yǔ)句
private static Statement stmt;
static {
conn = MyDbPool.getConn();
try {
stmt = conn.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void execute(String sql){
try {
stmt.execute(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//必須要關(guān)閉
public static void close(){
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MyDbPool.destory(conn);
}
}
}