---
title: "[转帖]java数据库链接池"
author: "abei1"
date: "2007-08-10T10:30:00Z"
tags: []
slug: "java"
draft: false
lastmod: "2007-08-10T10:30:00Z"
id: 110796
url: "https://abei1.iteye.com/blog/110796"
---

首先说明一下，这个数据库链接池不是我写的。是我在网上找到的，由于代码并不全，因此进行了一些填充。可以正常运行了。所以贴出来希望能帮到需要的人。

       这个数据库链接池的好处在于当用户从数据库链接池中的到连接后，并不需要特殊的方法将链接关闭，直接用close方法就可以关闭了。废话少说，上代码！！！！

      再次说明一下，以下的代码是根据网上得到的部分代码填充得到的，并不代表没有错误。如果那位高手能将代码完善感激不尽。

     下面的一段代码是一些数据库的属性。

java 代码

01. public class ConnectionParam {
02. private String driver = null;                                //数据库驱动程序
03. private String host = null;                                        //数据连接的URL
04. private String user = null;                                        //数据库用户名
05. private String password = null;                                //数据库密码
06. private String dataBase= null;
07. private String url = null;
08. private int minConnection = 0;                //初始化连接数
09. private int maxConnection = 0;                //最大连接数
10. private long timeoutValue = 0;            //连接的最大空闲时间
11. private long waitTime = 0;                //取连接的时候如果没有可用连接最大的等待时间
12. public ConnectionParam(){
13. super();
14. try {
15. String tmp = null;
16. int value = 0;
17. //CommonUtil.getPropertie("");方法是自己写的一个从属性文件中读取信息的方法。
18. this.driver = CommonUtil.getPropertie("driver");
19. this.host = CommonUtil.getPropertie("host");
20. this.user = CommonUtil.getPropertie("user");
21. this.password = CommonUtil.getPropertie("password");
22. this.dataBase= CommonUtil.getPropertie("dataBase");
23. this.url =CommonUtil.getPropertie("url");
24. tmp = CommonUtil.getPropertie("maxConnection");
25. value = 0;
26. if(CommonUtil.isNull(tmp)){
27. value = 0;
28. }else{
29. value = Integer.parseInt(tmp);
30. }
31. this.maxConnection = value;
32. tmp = CommonUtil.getPropertie("timeoutValue");
33. value = 0;
34. if(CommonUtil.isNull(tmp)){
35. value = 0;
36. }else{
37. value = Integer.parseInt(tmp);
38. }
39. this.timeoutValue = value;
40. tmp = CommonUtil.getPropertie("waitTime");
41. value = 0;
42. if(CommonUtil.isNull(tmp)){
43. value = 0;
44. }else{
45. value = Integer.parseInt(tmp);
46. }
47. this.waitTime = value;
48. } catch (IOException e) {
49. // TODO Auto-generated catch block
50. e.printStackTrace();
51. }
52. }
53. }

    下面这段代码是实现连接池的，其中的一些方法并没有实现。请各位见谅。

java 代码

001. import java.io.PrintWriter;
002. import java.sql.Connection;
003. import java.sql.DriverManager;
004. import java.sql.SQLException;
005. import java.util.ArrayList;
006. import java.util.Iterator;
007. import java.util.List;
008. import javax.sql.DataSource;
009. public class DataSourceImpl implements DataSource {
010. private ConnectionParam connParam = null;
011. private List conns = null;
012. public DataSourceImpl(ConnectionParam param){
013. conns = new ArrayList();
014. this.connParam = param;
015. }
016. public Connection getConnection() throws SQLException {
017. //首先从连接池中找出空闲的对象
018. Connection conn = getFreeConnection(0);
019. Connection conn2 = null;
020. if(conn == null){
021. //判断是否超过最大连接数,如果超过最大连接数
022. //则等待一定时间查看是否有空闲连接,否则抛出异常告诉用户无可用连接
023. if(getConnectionCount() &gt;= connParam.getMaxConnection())
024. conn = getFreeConnection(connParam.getWaitTime());
025. else{//没有超过连接数，重新获取一个数据库的连接
026. try {
027. Class.forName(connParam.getDriver()).newInstance();
028. conn2 = DriverManager.getConnection(connParam.getUrl(),
029. connParam.getUser(), connParam.getPassword());
030. } catch (InstantiationException e) {
031. e.printStackTrace();
032. } catch (IllegalAccessException e) {
033. e.printStackTrace();
034. } catch (ClassNotFoundException e) {
035. e.printStackTrace();
036. }
037. //代理将要返回的连接对象
038. \_Connection \_conn = new \_Connection(conn2,true);
039. synchronized(conns){
040. conns.add(\_conn);
041. }
042. conn = \_conn.getConnection();
043. }
044. }
045. return conn;
046. }
047. public Connection getConnection(String username, String password)
048. throws SQLException {
049. //首先从连接池中找出空闲的对象
050. Connection conn = getFreeConnection(0);
051. Connection conn2 = null;
052. if(conn == null){
053. //判断是否超过最大连接数,如果超过最大连接数
054. //则等待一定时间查看是否有空闲连接,否则抛出异常告诉用户无可用连接
055. if(getConnectionCount() &gt;= connParam.getMaxConnection())
056. conn = getFreeConnection(connParam.getWaitTime());
057. else{//没有超过连接数，重新获取一个数据库的连接
058. connParam.setUser(username);
059. connParam.setPassword(password);
060. try {
061. Class.forName(connParam.getDriver()).newInstance();
062. conn2 = DriverManager.getConnection(connParam.getUrl(),
063. username, password);
064. } catch (InstantiationException e) {
065. // TODO Auto-generated catch block
066. e.printStackTrace();
067. } catch (IllegalAccessException e) {
068. // TODO Auto-generated catch block
069. e.printStackTrace();
070. } catch (ClassNotFoundException e) {
071. // TODO Auto-generated catch block
072. e.printStackTrace();
073. }
074. //代理将要返回的连接对象
075. \_Connection \_conn = new \_Connection(conn2,true);
076. synchronized(conns){
077. conns.add(\_conn);
078. }
079. conn = \_conn.getConnection();
080. }
081. }
082. return conn;
083. }
084. public PrintWriter getLogWriter() throws SQLException {
085. // TODO Auto-generated method stub
086. return null;
087. }
088. public int getLoginTimeout() throws SQLException {
089. // TODO Auto-generated method stub
090. return 0;
091. }
092. public void setLogWriter(PrintWriter out) throws SQLException {
093. // TODO Auto-generated method stub
094. }
095. public void setLoginTimeout(int seconds) throws SQLException {
096. // TODO Auto-generated method stub
097. }
098. public void initConnection(){
099. //       TODO Auto-generated method stub
100. }
101. public void stop(){
102. //       TODO Auto-generated method stub
103. }
104. /\**
105. * 从连接池中取一个空闲的连接
106. * @param nTimeout        如果该参数值为0则没有连接时只是返回一个null
107. * 否则的话等待nTimeout毫秒看是否还有空闲连接，如果没有抛出异常
108. * @return Connection
109. * @throws SQLException
110. \*/
111. protected synchronized Connection getFreeConnection(long nTimeout)
112. throws SQLException
113. {
114. Connection conn = null;
115. Iterator iter = conns.iterator();
116. while(iter.hasNext()){
117. \_Connection \_conn = (\_Connection)iter.next();
118. if(!\_conn.isInUse()){
119. conn = \_conn.getConnection();
120. \_conn.setInUse(true);
121. break;
122. }
123. }
124. if(conn == null && nTimeout &gt; 0){
125. //等待nTimeout毫秒以便看是否有空闲连接
126. try{
127. Thread.sleep(nTimeout);
128. }catch(Exception e){}
129. conn = getFreeConnection(0);
130. if(conn == null)
131. throw new SQLException("没有可用的数据库连接");
132. }
133. return conn;
134. }
135. /\**
136. * 关闭该连接池中的所有数据库连接
137. * @return int 返回被关闭连接的个数
138. * @throws SQLException
139. \*/
140. public int close() throws SQLException
141. {
142. int cc = 0;
143. SQLException excp = null;
144. Iterator iter = conns.iterator();
145. while(iter.hasNext()){
146. try{
147. ((\_Connection)iter.next()).close();
148. cc ++;
149. }catch(Exception e){
150. if(e instanceof SQLException)
151. excp = (SQLException)e;
152. }
153. }
154. if(excp != null)
155. throw excp;
156. return cc;
157. }
158. /\**
159. * 返回当前链接的个数
160. * @return
161. \*/
162. private int getConnectionCount(){
163. Iterator iter = conns.iterator();
164. int count = 0;
165. while(iter.hasNext()){
166. \_Connection \_conn = (\_Connection)iter.next();
167. if(\_conn.isInUse()){
168. count++;
169. }
170. }
171. return count;
172. }
173. }

下面的是一个代理类。用来实现直接用close关闭连接。

java 代码

01. import java.lang.reflect.InvocationHandler;
02. import java.lang.reflect.Method;
03. import java.lang.reflect.Proxy;
04. import java.sql.Connection;
05. import java.sql.SQLException;
06. public class \_Connection implements InvocationHandler {
07. private final static String CLOSE\_METHOD\_NAME = "close";
08. private Connection conn = null;
09. //数据库的忙状态
10. private boolean inUse = false;
11. //用户最后一次访问该连接方法的时间
12. private long lastAccessTime = System.currentTimeMillis();
13. \_Connection(Connection conn, boolean inUse){
14. this.conn = conn;
15. this.inUse = inUse;
16. }
17. /\**
18. * Returns the conn.
19. * @return Connection
20. \*/
21. public Connection getConnection() {
22. //返回数据库连接conn的接管类，以便截住close方法
23. Connection conn2 = (Connection)Proxy.newProxyInstance(
24. conn.getClass().getClassLoader(),
25. conn.getClass().getInterfaces(),this);
26. return conn2;
27. }
28. /\**
29. * 该方法真正的关闭了数据库的连接
30. * @throws SQLException
31. \*/
32. void close() throws SQLException{
33. //由于类属性conn是没有被接管的连接，因此一旦调用close方法后就直接关闭连接
34. conn.close();
35. }
36. /\**
37. * Returns the inUse.
38. * @return boolean
39. \*/
40. public boolean isInUse() {
41. return inUse;
42. }
43. /\**
44. * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object)
45. \*/
46. public Object invoke(Object proxy, Method m, Object\[] args)
47. throws Throwable
48. {
49. Object obj = null;
50. //判断是否调用了close的方法，如果调用close方法则把连接置为无用状态
51. if(CLOSE\_METHOD\_NAME.equals(m.getName()))
52. setInUse(false);
53. else
54. obj = m.invoke(conn, args);
55. //设置最后一次访问时间，以便及时清除超时的连接
56. lastAccessTime = System.currentTimeMillis();
57. return obj;
58. }
59. /\**
60. * Returns the lastAccessTime.
61. * @return long
62. \*/
63. public long getLastAccessTime() {
64. return lastAccessTime;
65. }
66. /\**
67. * Sets the inUse.
68. * @param inUse The inUse to set
69. \*/
70. public void setInUse(boolean inUse) {
71. &