之前的连接在每次使用完后都会关闭,而创建连接的成本是很高的,所以现在的想法就是能不能在程序开始的时候创建一批连接,放入连接池中,当需要使用的时候就从连接池中取连接,使用完毕后再将连接放回到连接池中
1,创建一个数据源
package cn.itcast.jdbc.dataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
public class MyDataSource {
private static String url = "jdbc:mysql://localhost:3306/jdbc";
private static String user = "root";
private static String password = "123456";
public static void main(String[] args) {
}
private LinkedList<Connection> connectionPool = new LinkedList<Connection>(); //连接池
public MyDataSource(){
try{
for(int i=0;i<10;i++){ //MyDataSource创建时就建立10个连接
this.connectionPool.addLast(this.createConnection());
}
}catch(SQLException e){
throw new ExceptionInInitializerError();
}
}
public Connection getConnection(){
return this.connectionPool.removeFirst();
}
public void free(Connection conn){ //释放连接,实际上就是重新加入到连接池
this.connectionPool.addLast(conn);
}
private Connection createConnection()throws SQLException{
return DriverManager.getConnection(url,user,password);
}
}
2,修改工具类
package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import cn.itcast.jdbc.dataSource.MyDataSource;
public final class JdbcUtils {
private static MyDataSource myDataSource = null;
private JdbcUtils() {
}
static {
try {
Class.forName("com.mysql.jdbc.Driver");
myDataSource = new MyDataSource();
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException {
// return DriverManager.getConnection(url, user, password);
return myDataSource.getConnection(); // 取连接
}
public static void free(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null)
// conn.close();
myDataSource.free(conn); // 释放连接
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}