今天写了些测试,留下一个简易的连接池,其实用框架好用,但是相对于小型的开发速度来说 javabean+servlet速度似乎更快,这里留点记录,以备日后心血来潮完善把。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Vector;
 
public class DBManager {
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	private Statement stmt = null;
	private ResultSet rs = null;
	private static Vector dsprool = new Vector<connection>();
 
	/**
	 * 
	 */
	private DBManager() {
	}
 
	public static DBManager _INSTANCE = new DBManager();
 
	public static DBManager getDBManager() {
		return _INSTANCE;
	}
 
	public Connection getConnection() {
		// return getPoolConn();
		try {
			Class.forName(Config.getConfig().getProperty("DBDRIVER"));
		} catch (ClassNotFoundException e) {
			System.out.println("加载驱动失败");
		}
		try {
			conn = DriverManager.getConnection(Config.getConfig().getProperty(
					"DBURL"), Config.getConfig().getProperty("DBUSER"), Config
					.getConfig().getProperty("DBPASSWORD"));
		} catch (SQLException e) {
			System.out.println("数据库用户名密码不匹配");
		}
		// System.out.println("获取连接");
		return conn;
	}
 
	/**
	 * 创建连接池
	 */
	public void CreateDS() {
		for (int i = 0; i < 50; i++) {
			dsprool.add(getConnection());
		}
		System.out.println("create ds over……");
	}
 
	/**
	 * 获取连接池链接
	 * 
	 * @return
	 */
	public Connection getDSConn() {
		if (dsprool.isEmpty()) {
			try {
				Thread.sleep(1000 * 2);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			getDSConn();
		} else {
			return (Connection) dsprool.remove(0);
		}
		return null;
	}
 
	/**
	 * 链接回池
	 * 
	 * @param conn
	 */
	public void BackConn(Connection conn) {
		if (conn != null) {
			dsprool.add(conn);
		}
	}
 
	/**
	 * 销毁连接池
	 */
	public void DestoryDS() {
		Iterator it = dsprool.iterator();
		while (it.hasNext()) {
			Connection conns = (Connection) it.next();
			if (conns != null) {
				try {
					conns.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

你可以在项目启动的时候创建连接池,来初始化。这个很建议,建议修改测试使用。