📄 jdbcdbsimp.java
字号:
package com.datasource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
public class JDBCDBSImp implements DBSource {
private String url;
private String user;
private String passwd;
private String driverName;
private int iPoolSize;
private ArrayList<Connection> lstPool = new ArrayList<Connection>();
public JDBCDBSImp(String url, String user, String passwd, String driverName, int poolSize) {
this.url = url;
this.user = user;
this.passwd = passwd;
this.driverName = driverName;
this.iPoolSize = poolSize;
this.initPool();
}
public void initPool(){
Connection conn = null;
int j = 0; //������l�Ӹ���
for(int i=0;i<iPoolSize;i++){
conn = this.addConnection(this.url, this.user, this.passwd, this.driverName);
if(conn!=null){
lstPool.add(conn);
j++;
}
conn = null;
}
if(j==0){
System.out.println("连接池初始化失败,请检查配置");
//可在此处抛出异常
}
else{
System.out.println("初始化连接池:"+j+"个连接创建");
}
}
/**
* 加载数据库库驱动,并获得一个连接
* @param url数据库URL jdbc:oracle:thin:@192.168.1.109:1521:ORCL
* @param user数据库的用户名
* @param passwd数据库的密码
* @param driverName数据库驱动程序
* @return
*/
private Connection addConnection(String url, String user, String passwd,
String driverName) {
Connection conn = null;
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url, user, passwd);
} catch (ClassNotFoundException e) {
System.out.println("=========δ������̳���=========");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("=========δ�õ�l�ӣ�=========");
e.printStackTrace();
} catch (Exception e) {
System.out.println("=========δ֪�쳣(JDBCDSImp)=========");
e.printStackTrace();
}
return conn;
}
/**
*
*
* 从池中拿出连接
*
*/
public synchronized Connection getConnection() {
Connection conn=null;
if(lstPool.size()==0){
conn = this.addConnection(this.url, this.user, this.passwd, this.driverName);
//如果获取失败,则继续两次��
if(conn == null){
for(int i=0;i<2;i++){
conn = this.addConnection(this.url, this.user, this.passwd, this.driverName);
if(conn!=null) break;
}
}
}
else{
conn = lstPool.get(0);
lstPool.remove(0);
}
return conn;
}
/**
* 将有效连接放回到连接池,便于后续使用
*/
public synchronized void putConnection(Connection conn){
if(conn == null) return;
try{
if(conn.isClosed()) return;
}catch(Exception e){
return;
}
lstPool.add(conn);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -