日期:2014-05-16  浏览次数:20424 次

一种连接池的实现方案

DB.java


package wkx.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DB {
	
	public static int executeUpdate(String sql) {
		int ans = 0;
		Connection conn = DB.getConn();
		Statement stmt = DB.getStmt(conn);
		try {
			ans = stmt.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DB.close(stmt);
			DB.close(conn);
		}
		return ans;
	}
	
	public static Connection getConn() {
		return ConnPool.getConn();
	}

	public static Statement getStmt(Connection conn) {
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stmt;
	}

	
	
	public static ResultSet executeQuery(Statement stmt, String sql) {
		//System.out.println("QUERY:"+sql);
		ResultSet rs = null;
		try {
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	public static void close(Connection conn) {
		ConnPool.close(conn);
	}

	public static void close(Statement stmt) {
		try {
			if (stmt != null) {
				stmt.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		stmt = null;
	}

	public static void close(ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		rs = null;
	}
	
	public static void closeAll(Connection conn,Statement stmt){
		DB.close(conn);
		DB.close(stmt);
	}
	
	public static void closeAll(Connection conn,Statement stmt,ResultSet rs){
		DB.close(conn);
		DB.close(stmt);
		DB.close(rs);
	}
	
}


ConnPool.java


package wkx.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

public class ConnPool {
	
	public static final int MAX_CONN_NUM = 10;
	private static LinkedList<Connection> conns = null;
	private static int connNum = 0;
	
	static {
		conns = new LinkedList<Connection>();
	}
	
	private ConnPool(){
		
	}
	
	public static Connection getConn() {
		Connection conn = null;
		if(conns.size()==0){
			try {
				Class.forName("com.mysql.jdbc.Driver");
				conn = DriverManager.getConnection(
						"jdbc:mysql://localhost:3306/project", "root", "root");
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			connNum++;
		}else{
			conn=conns.pop();
		}
		/**
		 * 
		 */
		ConnPool.printStatus();
		return conn;
	}
	
	public static void close(Connection conn) {
		if(connNum>ConnPool.MAX_CONN_NUM){
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			conn = null;
			connNum--;
		}else{
			conns.push(conn);
		}
		
		ConnPool.printStatus();
	}
	
	public static void printStatus(){
		System.out.println("闲置连接数:"+conns.size()+"  总连接数:"+connNum+"  已使用连接数:"+(connNum-conns.size()));
	}
	
}