- package cn.itcast.jdbc.datasource;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.LinkedList;
- import java.util.List;
- public class MyDataSource {
-
- private static String url="jdbc:mysql://localhost:3306/jdbc";
- private static String user="root";
- private static String password="admin";
-
- private LinkedList<Connection> connectionsPool=new LinkedList<Connection>();
-
- public MyDataSource(){
- for(int i=0;i<10;i++){
- try {
- //先入先出的算法
- this.connectionsPool.addLast(this.createConnection());
- } catch (SQLException e) {
- throw new ExceptionInInitializerError(e);
- }
- }
- }
-
- public Connection getConnection(){
- return this.connectionsPool.removeFirst();
- }
- private Connection createConnection() throws SQLException{
- return DriverManager.getConnection(url, user, password);
- }
-
- public void free(Connection conn){
- this.connectionsPool.addLast(conn);
- }
- }
- package cn.itcast.jdbc;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import cn.itcast.jdbc.datasource.MyDataSource;
- public final class JdbcUtils {
- private static String url="jdbc:mysql://localhost:3306/jdbc";
- private static String user="root";
- private static String password="admin";
- private static MyDataSource myDataSource=null;
- private JdbcUtils(){
- }
- static{
- try{
- Class.forName("com.mysql.jdbc.Driver");
- myDataSource=new MyDataSource();
- }catch(ClassNotFoundException 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{
- if(conn!=null)
- try{
- //conn.close();
- myDataSource.free(conn);
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
- }
- }
编写一个基本的连接池来实现连接的复用。
注意:removeLast是LinkedList所独有的方法。
所以只能写private LinkedList connectionsPool=new LinkedList();
不能写成private List connectionsPool=new LinkedList();这种面向接口的编程。切记,切记!
阅读(2686) | 评论(0) | 转发(0) |