1 package com.curriculumDesign.database;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.util.ArrayList;
6
7 public class ConnectionPool {
8
9 private static int maxConnectNum = 10;
10
11 private java.sql.Connection conn[] = new Connection[maxConnectNum];
12
13 private static ArrayList connectPool = new ArrayList();
14
15 private static int flag = 0;
16
17 public ConnectionPool() {
18 if (flag == 0) {
19 init();
20 }
21 }
22
23 private Connection getConnectionFromDatabase() {
24 Connection trueConn = null;
25 try {
26 Class.forName("com.mysql.jdbc.Driver").newInstance();
27 String url = "jdbc:mysql://localhost:3306/book_store?user=root&password=";
28 trueConn = DriverManager.getConnection(url);
29 } catch (Exception ex) {
30 System.out.println("数据连接出错了:" + ex.toString());
31 }
32 return trueConn;
33 }
34
35 //这里建立所有的连接;
36 private void init() {
37 for (int i = 0; i < maxConnectNum; i++) {
38 conn[i] = getConnectionFromDatabase();
39 connectPool.add(i, conn[i]);
40 }
41 flag = 1;
42 }
43
44 //从连接池中取得一个可用的连接
45 public Connection getConnection() {
46 Connection conn = null;
47 if (connectPool.size() == 0) {
48 try {
49 java.lang.Thread.sleep(1000);
50 getConnection();
51 } catch (InterruptedException ex) {
52 System.out.println("连接全部用光,这里sleep出错了.");
53 }
54 } else {
55 conn = (Connection) connectPool.remove(0);
56 }
57
58 return conn;
59 }
60
61 //提供给外部程序调用,不用的连接放回连接池当中...
62 public boolean release(Connection conn) {
63 return connectPool.add(conn);
64 }
65 }
摘抄别人的,并非原创