dataSource.setUsername(username);
dataSource.setPassword(password);
//初始化连接数
if(initialSize!=null){
dataSource.setInitialSize(Integer.parseInt(initialSize));
}
//最小空闲连接
if(minIdle!=null){
dataSource.setMinIdle(Integer.parseInt(minIdle));
}
//最大空闲连接
if(maxIdle!=null){
dataSource.setMaxIdle(Integer.parseInt(maxIdle));
}
//超时回收时间(以毫秒为单位)
if(maxWait!=null){
dataSource.setMaxWait(Long.parseLong(maxWait));
}
//最大连接数
if(maxActive!=null){
if(!maxActive.trim().equals("0")){
dataSource.setMaxActive(Integer.parseInt(maxActive));
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("创建连接池失败!请检查设置!!!");
}
}
}
步骤四:添加获取连接的方法
在ConnectionSource类中添加获取连接的方法,getConnection,代码如下所示:
public static synchronized Connection getConnection() throws SQLException{
if(dataSource==null){
init();
}
Connection con=null;
if(dataSource!=null){
con=dataSource.getConnection();
}
return con;
}
步骤四
:重构EmpDAO类
重构EmpDAO类,在该类中使用ConnectionSource类的getConnection()方法获取连接,代码如下所示:
package dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class EmpDAO {
public static void main(String [] args){
EmpDAO dao=new EmpDAO();
dao.findAll();
}
public void findAll(){
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
try {
con=ConnectionSource.getConnection();
stmt=con.createStatement();
rs=stmt.executeQuery("select empno,ename,sal,hiredate from emp;");
while(rs.next()){
System.out.println(rs.getInt("empno")+","+rs.getString("ename")+","+rs.getDouble("sal")+","+rs.getDate("hiredate"));
}
} catch (SQLException e) {
System.out.println("数据库访问异常!");
throw new RuntimeException(e);
}
finally{
try {
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(con!=null){
con.close();
}
} catch (SQLException e) {
System.out.println("释放资源时发生异常!");
}
}
}
}
在此,调用Connection类的close方法关闭连接,会将该连接归还到连接池中。
运行EmpDAO类,输出如下:

和之前的案例输出结果一致。
本节,先更新到这里,下次继续写:如何更新和插入Emp数据。