如果每次查询数据库调用查询语句的同时调用connection都要开启又关闭,就会发现是一件很耗时的操作。
所有这个时候可以建立一种思想,可不可以把数据库开启的连接一下子开启N个,然后保存到一个数据结构中,当你要取得时候只要从集合里取出,不用的时候再关掉。
》》代码
package com.yiki.dataSource; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.LinkedList; public class myDataSource { private static String url; private static String user; private static String password; private static int initSize = 3;// 初始化连接池的连接数 private static int MaxSize = 5;// 假设数据库可以创建10个连接 private static int CurrentSize = 0;// 当前连接数 static { url = "jdbc:mysql://localhost:3306/yiki?useUnicode=true&characterEncoding=gb2312"; user = "root"; password = "******"; } LinkedList<Connection> conPool = new LinkedList<Connection>();// 创建链表来存储连接 public myDataSource() { for (int i = 0; i < initSize; i++) {// 连接池可以容纳5个连接 try { this.conPool.addLast(this.createCon()); myDataSource.CurrentSize++; } catch (SQLException e) { e.printStackTrace(); } } } public Connection getCon() throws Exception { synchronized (conPool) {// 加锁,保证多个线程不会难道同一个链接 if (this.conPool.size() > 0) {// 看看还有没有 return this.conPool.removeFirst();// 就是从连接池里取出来(连接池是链表,移走表头 } // else表已经没有连接了,就再创建连接 if (myDataSource.CurrentSize < MaxSize) {// 如果请求的连接超载了,可在数据库允许的连接上再创建连接 myDataSource.CurrentSize++; return this.createCon(); } throw new SQLException("连接池已没有链接"); } } public void free(Connection con) {// 释放连接就是把连接放回连接池 this.conPool.addLast(con); } private Connection createCon() throws SQLException {// 创建连接 return DriverManager.getConnection(url, user, password); } }
package com.yiki.dataSource; import java.sql.Connection; public class DButil { private static String driver; private static myDataSource source ; static { driver = "com.mysql.jdbc.Driver"; source = new myDataSource(); } public static Connection open() { try { Class.forName(driver); return source.getCon(); } catch (Exception e) { e.printStackTrace(); System.out.println("连接错误"); } return null; } public static void close(Connection con) { if (con != null) { try { //con.close();拦截close方法见下章 source.free(con); } catch (Exception e) { e.printStackTrace(); } } } }
package com.yiki.dataSource; import java.sql.Connection; public class test { public static void main(String[] args) { for (int i = 0; i < 5; i++) { Connection conn = DButil.open(); System.out.println(conn); DButil.close(conn); } } }》》测试
发现重复即成功。