Java数据库链接池实现原理

 

 
通常来讲,Java应用程序访问数据库的过程是:
  ①装载数据库驱动程序;
  ②经过jdbc创建数据库链接;
  ③访问数据库,执行sql语句;

  ④断开数据库链接。java

 

[java] view plain copy
 
print?
  1. public class DBConnection {   
  2.   
  3.     private Connection con;         //定义数据库链接类对象  
  4.     private PreparedStatement pstm;   
  5.     private String user="root";     //链接数据库用户名  
  6.     private String password="123456";       //链接数据库密码  
  7.     private String driverName="com.mysql.jdbc.Driver";  //数据库驱动  
  8.     private String url="jdbc:mysql://localhost:3306/qingqingtuan";        
  9. //链接数据库的URL,后面的是为了防止插入数据 库出现乱码,?useUnicode=true&characterEncoding=UTF-8  
  10. //构造函数  
  11. public DBConnection(){  
  12.       
  13. }  
  14. /**建立数据库链接*/  
  15. public Connection getConnection(){  
  16.     try{  
  17.         Class.forName("com.mysql.jdbc.Driver");  
  18.     }catch(ClassNotFoundException e){  
  19.         System.out.println("加载数据库驱动失败!");  
  20.         e.printStackTrace();  
  21.     }  
  22.     try {  
  23.         con=DriverManager.getConnection(url,user,password);     //获取数据库链接  
  24.     } catch (SQLException e) {  
  25.         System.out.println("建立数据库链接失败!");  
  26.         con=null;  
  27.         e.printStackTrace();  
  28.     }  
  29.     return con;                 //返回数据库链接对象  
  30. }  
  31.  List<Shop> mShopList=new ArrayList<Shop>();  
  32.          mConnection=new DBConnection().getConnection();  
  33.          if(mConnection!=null){           
  34.             try {  
  35.                 String sql="select * from shop";  
  36.                 PreparedStatement pstm=mConnection.prepareStatement(sql);  
  37.                 ResultSet rs=pstm.executeQuery();  
  38.                 while(rs.next()){  
  39.                                 ......//封装PoPj的操做  
  40.                                 }  
  41.                                 rs.close();  
  42.                 pstm.close();        
  43.             } catch (SQLException e) {                
  44.                 e.printStackTrace();  
  45.             }finally{  
  46.                 try {  
  47.                     if(mConnection!=null){  
  48.                         mConnection.close();  
  49.                     }                     
  50.                 } catch (SQLException e) {  
  51.                     e.printStackTrace();  
  52.                 }  
  53.             }   
 
 

 

                     

 

程序开发过程当中,存在不少问题:mysql

首先,每一次web请求都要创建一次数据库链接。创建链接是一个费时的活动,每次都得花费0.05s~1s的时间,并且系统还要分配内存资源。这个时间对于一次或几回数据库操做,或许感受不出系统有多大的开销。web

但是对于如今的web应用,尤为是大型电子商务网站,同时有几百人甚至几千人在线是很正常的事。在这种状况下,频繁的进行数据库链接操做势必占用不少的系统资源,网站的响应速度一定降低,严重的甚至会形成服务器的崩溃。不是危言耸听,这就是制约某些电子商务网站发展的技术瓶颈问题。其次,对于每一次数据库链接,使用完后都得断开。不然,若是程序出现异常而未能关闭,将会致使数据库系统中的内存泄漏,最终将不得不重启数据库sql

     经过上面的分析,咱们能够看出来,“数据库链接”是一种稀缺的资源,为了保障网站的正常使用,应该对其进行妥善管理。实现getConnection()从链接库中获取一个可用的链接
③ returnConnection(conn) 提供将链接放回链接池中方法
数据库

 

ConnectionPool.java服务器

 

[java] view plain copy
 
print?
  1. //////////////////////////////// 数据库链接池类 ConnectionPool.java ////////////////////////////////////////  
  2.   
  3. /* 
  4.  这个例子是根据POSTGRESQL数据库写的, 
  5.  请用的时候根据实际的数据库调整。 
  6.  调用方法以下: 
  7.  ① ConnectionPool connPool  
  8.  = new ConnectionPool("com.microsoft.jdbc.sqlserver.SQLServerDriver" 
  9.  ,"jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=MyDataForTest" 
  10.  ,"Username" 
  11.  ,"Password"); 
  12.  ② connPool .createPool(); 
  13.  Connection conn = connPool .getConnection(); 
  14.  connPool.returnConnection(conn);  
  15.  connPool.refreshConnections(); 
  16.  connPool.closeConnectionPool(); 
  17.  */  
  18. import java.sql.Connection;  
  19. import java.sql.DatabaseMetaData;  
  20. import java.sql.Driver;  
  21. import java.sql.DriverManager;  
  22. import java.sql.SQLException;  
  23. import java.sql.Statement;  
  24. import java.util.Enumeration;  
  25. import java.util.Vector;  
  26.   
  27. public class ConnectionPool {  
  28.     private String jdbcDriver = ""; // 数据库驱动  
  29.     private String dbUrl = ""; // 数据 URL  
  30.     private String dbUsername = ""; // 数据库用户名  
  31.     private String dbPassword = ""; // 数据库用户密码  
  32.     private String testTable = ""; // 测试链接是否可用的测试表名,默认没有测试表  
  33.       
  34.     private int initialConnections = 10; // 链接池的初始大小  
  35.     private int incrementalConnections = 5;// 链接池自动增长的大小  
  36.     private int maxConnections = 50; // 链接池最大的大小  
  37.     private Vector connections = null; // 存放链接池中数据库链接的向量 , 初始时为 null  
  38.     // 它中存放的对象为 PooledConnection 型  
  39.   
  40.     /** 
  41.      * 构造函数 
  42.      *  
  43.      * @param jdbcDriver 
  44.      *            String JDBC 驱动类串 
  45.      * @param dbUrl 
  46.      *            String 数据库 URL 
  47.      * @param dbUsername 
  48.      *            String 链接数据库用户名 
  49.      * @param dbPassword 
  50.      *            String 链接数据库用户的密码 
  51.      *  
  52.      */  
  53.     public ConnectionPool(String jdbcDriver, String dbUrl, String dbUsername,  
  54.             String dbPassword) {  
  55.         this.jdbcDriver = jdbcDriver;  
  56.         this.dbUrl = dbUrl;  
  57.         this.dbUsername = dbUsername;  
  58.         this.dbPassword = dbPassword;  
  59.     }  
  60.   
  61.     /** 
  62.      * 返回链接池的初始大小 
  63.      *  
  64.      * @return 初始链接池中可得到的链接数量 
  65.      */  
  66.     public int getInitialConnections() {  
  67.         return this.initialConnections;  
  68.     }  
  69.     /** 
  70.      * 设置链接池的初始大小 
  71.      *  
  72.      * @param 用于设置初始链接池中链接的数量 
  73.      */  
  74.     public void setInitialConnections(int initialConnections) {  
  75.         this.initialConnections = initialConnections;  
  76.     }  
  77.     /** 
  78.      * 返回链接池自动增长的大小 、 
  79.      *  
  80.      * @return 链接池自动增长的大小 
  81.      */  
  82.     public int getIncrementalConnections() {  
  83.         return this.incrementalConnections;  
  84.     }  
  85.     /** 
  86.      * 设置链接池自动增长的大小 
  87.      *  
  88.      * @param 链接池自动增长的大小 
  89.      */  
  90.   
  91.     public void setIncrementalConnections(int incrementalConnections) {  
  92.         this.incrementalConnections = incrementalConnections;  
  93.     }  
  94.     /** 
  95.      * 返回链接池中最大的可用链接数量 
  96.      *  
  97.      * @return 链接池中最大的可用链接数量 
  98.      */  
  99.     public int getMaxConnections() {  
  100.         return this.maxConnections;  
  101.     }  
  102.     /** 
  103.      * 设置链接池中最大可用的链接数量 
  104.      *  
  105.      * @param 设置链接池中最大可用的链接数量值 
  106.      */  
  107.     public void setMaxConnections(int maxConnections) {  
  108.         this.maxConnections = maxConnections;  
  109.     }  
  110.   
  111.     /** 
  112.      * 获取测试数据库表的名字 
  113.      *  
  114.      * @return 测试数据库表的名字 
  115.      */  
  116.   
  117.     public String getTestTable() {  
  118.         return this.testTable;  
  119.     }  
  120.   
  121.     /** 
  122.      * 设置测试表的名字 
  123.      *  
  124.      * @param testTable 
  125.      *            String 测试表的名字 
  126.      */  
  127.   
  128.     public void setTestTable(String testTable) {  
  129.         this.testTable = testTable;  
  130.     }  
  131.   
  132.     /** 
  133.      *  
  134.      * 建立一个数据库链接池,链接池中的可用链接的数量采用类成员 initialConnections 中设置的值 
  135.      */  
  136.   
  137.     public synchronized void createPool() throws Exception {  
  138.         // 确保链接池没有建立  
  139.         // 若是链接池己经建立了,保存链接的向量 connections 不会为空  
  140.         if (connections != null) {  
  141.             return; // 若是己经建立,则返回  
  142.         }  
  143.         // 实例化 JDBC Driver 中指定的驱动类实例  
  144.         Driver driver = (Driver) (Class.forName(this.jdbcDriver).newInstance());  
  145.         DriverManager.registerDriver(driver); // 注册 JDBC 驱动程序  
  146.         // 建立保存链接的向量 , 初始时有 0 个元素  
  147.         connections = new Vector();  
  148.         // 根据 initialConnections 中设置的值,建立链接。  
  149.         createConnections(this.initialConnections);  
  150.         // System.out.println(" 数据库链接池建立成功! ");  
  151.     }  
  152.   
  153.     /** 
  154.      * 建立由 numConnections 指定数目的数据库链接 , 并把这些链接 放入 connections 向量中 
  155.      *  
  156.      * @param numConnections 
  157.      *            要建立的数据库链接的数目 
  158.      */  
  159.   
  160.     private void createConnections(int numConnections) throws SQLException {  
  161.         // 循环建立指定数目的数据库链接  
  162.         for (int x = 0; x < numConnections; x++) {  
  163.             // 是否链接池中的数据库链接的数量己经达到最大?最大值由类成员 maxConnections  
  164.             // 指出,若是 maxConnections 为 0 或负数,表示链接数量没有限制。  
  165.             // 若是链接数己经达到最大,即退出。  
  166.             if (this.maxConnections > 0  
  167.                     && this.connections.size() >= this.maxConnections) {  
  168.                 break;  
  169.             }  
  170.             // add a new PooledConnection object to connections vector  
  171.             // 增长一个链接到链接池中(向量 connections 中)  
  172.             try {  
  173.                 connections.addElement(new PooledConnection(newConnection()));  
  174.             } catch (SQLException e) {  
  175.                 System.out.println(" 建立数据库链接失败! " + e.getMessage());  
  176.                 throw new SQLException();  
  177.             }  
  178.             // System.out.println(" 数据库链接己建立 ......");  
  179.         }  
  180.     }  
  181.     /** 
  182.      * 建立一个新的数据库链接并返回它 
  183.      *  
  184.      * @return 返回一个新建立的数据库链接 
  185.      */  
  186.     private Connection newConnection() throws SQLException {  
  187.         // 建立一个数据库链接  
  188.         Connection conn = DriverManager.getConnection(dbUrl, dbUsername,  
  189.                 dbPassword);  
  190.         // 若是这是第一次建立数据库链接,即检查数据库,得到此数据库容许支持的  
  191.         // 最大客户链接数目  
  192.         // connections.size()==0 表示目前没有链接己被建立  
  193.         if (connections.size() == 0) {  
  194.             DatabaseMetaData metaData = conn.getMetaData();  
  195.             int driverMaxConnections = metaData.getMaxConnections();  
  196.             // 数据库返回的 driverMaxConnections 若为 0 ,表示此数据库没有最大  
  197.             // 链接限制,或数据库的最大链接限制不知道  
  198.             // driverMaxConnections 为返回的一个整数,表示此数据库容许客户链接的数目  
  199.             // 若是链接池中设置的最大链接数量大于数据库容许的链接数目 , 则置链接池的最大  
  200.             // 链接数目为数据库容许的最大数目  
  201.             if (driverMaxConnections > 0  
  202.                     && this.maxConnections > driverMaxConnections) {  
  203.                 this.maxConnections = driverMaxConnections;  
  204.             }  
  205.         }  
  206.         return conn; // 返回建立的新的数据库链接  
  207.     }  
  208.   
  209.     /** 
  210.      * 经过调用 getFreeConnection() 函数返回一个可用的数据库链接 , 若是当前没有可用的数据库链接,而且更多的数据库链接不能创 
  211.      * 建(如链接池大小的限制),此函数等待一会再尝试获取。 
  212.      *  
  213.      * @return 返回一个可用的数据库链接对象 
  214.      */  
  215.   
  216.     public synchronized Connection getConnection() throws SQLException {  
  217.         // 确保链接池己被建立  
  218.         if (connections == null) {  
  219.             return null; // 链接池还没建立,则返回 null  
  220.         }  
  221.         Connection conn = getFreeConnection(); // 得到一个可用的数据库链接  
  222.         // 若是目前没有可使用的链接,即全部的链接都在使用中  
  223.         while (conn == null) {  
  224.             // 等一会再试  
  225.             // System.out.println("Wait");  
  226.             wait(250);  
  227.             conn = getFreeConnection(); // 从新再试,直到得到可用的链接,若是  
  228.             // getFreeConnection() 返回的为 null  
  229.             // 则代表建立一批链接后也不可得到可用链接  
  230.         }  
  231.         return conn;// 返回得到的可用的链接  
  232.     }  
  233.   
  234.     /** 
  235.      * 本函数从链接池向量 connections 中返回一个可用的的数据库链接,若是 当前没有可用的数据库链接,本函数则根据 
  236.      * incrementalConnections 设置 的值建立几个数据库链接,并放入链接池中。 若是建立后,全部的链接仍都在使用中,则返回 null 
  237.      *  
  238.      * @return 返回一个可用的数据库链接 
  239.      */  
  240.     private Connection getFreeConnection() throws SQLException {  
  241.         // 从链接池中得到一个可用的数据库链接  
  242.         Connection conn = findFreeConnection();  
  243.         if (conn == null) {  
  244.             // 若是目前链接池中没有可用的链接  
  245.             // 建立一些链接  
  246.             createConnections(incrementalConnections);  
  247.             // 从新从池中查找是否有可用链接  
  248.             conn = findFreeConnection();  
  249.             if (conn == null) {  
  250.                 // 若是建立链接后仍得到不到可用的链接,则返回 null  
  251.                 return null;  
  252.             }  
  253.         }  
  254.         return conn;  
  255.     }  
  256.   
  257.     /** 
  258.      * 查找链接池中全部的链接,查找一个可用的数据库链接, 若是没有可用的链接,返回 null 
  259.      *  
  260.      * @return 返回一个可用的数据库链接 
  261.      */  
  262.   
  263.     private Connection findFreeConnection() throws SQLException {  
  264.         Connection conn = null;  
  265.         PooledConnection pConn = null;  
  266.         // 得到链接池向量中全部的对象  
  267.         Enumeration enumerate = connections.elements();  
  268.         // 遍历全部的对象,看是否有可用的链接  
  269.         while (enumerate.hasMoreElements()) {  
  270.             pConn = (PooledConnection) enumerate.nextElement();  
  271.             if (!pConn.isBusy()) {  
  272.                 // 若是此对象不忙,则得到它的数据库链接并把它设为忙  
  273.                 conn = pConn.getConnection();  
  274.                 pConn.setBusy(true);  
  275.                 // 测试此链接是否可用  
  276.                 if (!testConnection(conn)) {  
  277.                     // 若是此链接不可再用了,则建立一个新的链接,  
  278.                     // 并替换此不可用的链接对象,若是建立失败,返回 null  
  279.                     try {  
  280.                         conn = newConnection();  
  281.                     } catch (SQLException e) {  
  282.                         System.out.println(" 建立数据库链接失败! " + e.getMessage());  
  283.                         return null;  
  284.                     }  
  285.                     pConn.setConnection(conn);  
  286.                 }  
  287.                 break; // 己经找到一个可用的链接,退出  
  288.             }  
  289.         }  
  290.         return conn;// 返回找到到的可用链接  
  291.     }  
  292.   
  293.     /** 
  294.      * 测试一个链接是否可用,若是不可用,关掉它并返回 false 不然可用返回 true 
  295.      *  
  296.      * @param conn 
  297.      *            须要测试的数据库链接 
  298.      * @return 返回 true 表示此链接可用, false 表示不可用 
  299.      */  
  300.   
  301.     private boolean testConnection(Connection conn) {  
  302.         try {  
  303.             // 判断测试表是否存在  
  304.             if (testTable.equals("")) {  
  305.                 // 若是测试表为空,试着使用此链接的 setAutoCommit() 方法  
  306.                 // 来判断链接否可用(此方法只在部分数据库可用,若是不可用 ,  
  307.                 // 抛出异常)。注意:使用测试表的方法更可靠  
  308.                 conn.setAutoCommit(true);  
  309.             } else {// 有测试表的时候使用测试表测试  
  310.                 // check if this connection is valid  
  311.                 Statement stmt = conn.createStatement();  
  312.                 stmt.execute("select count(*) from " + testTable);  
  313.             }  
  314.         } catch (SQLException e) {  
  315.             // 上面抛出异常,此链接己不可用,关闭它,并返回 false;  
  316.             closeConnection(conn);  
  317.             return false;  
  318.         }  
  319.         // 链接可用,返回 true  
  320.         return true;  
  321.     }  
  322.   
  323.     /** 
  324.      * 此函数返回一个数据库链接到链接池中,并把此链接置为空闲。 全部使用链接池得到的数据库链接均应在不使用此链接时返回它。 
  325.      *  
  326.      * @param 需返回到链接池中的链接对象 
  327.      */  
  328.   
  329.     public void returnConnection(Connection conn) {  
  330.         // 确保链接池存在,若是链接没有建立(不存在),直接返回  
  331.         if (connections == null) {  
  332.             System.out.println(" 链接池不存在,没法返回此链接到链接池中 !");  
  333.             return;  
  334.         }  
  335.         PooledConnection pConn = null;  
  336.         Enumeration enumerate = connections.elements();  
  337.         // 遍历链接池中的全部链接,找到这个要返回的链接对象  
  338.         while (enumerate.hasMoreElements()) {  
  339.             pConn = (PooledConnection) enumerate.nextElement();  
  340.             // 先找到链接池中的要返回的链接对象  
  341.             if (conn == pConn.getConnection()) {  
  342.                 // 找到了 , 设置此链接为空闲状态  
  343.                 pConn.setBusy(false);  
  344.                 break;  
  345.             }  
  346.         }  
  347.     }  
  348.   
  349.     /** 
  350.      * 刷新链接池中全部的链接对象 
  351.      *  
  352.      */  
  353.   
  354.     public synchronized void refreshConnections() throws SQLException {  
  355.         // 确保链接池己创新存在  
  356.         if (connections == null) {  
  357.             System.out.println(" 链接池不存在,没法刷新 !");  
  358.             return;  
  359.         }  
  360.         PooledConnection pConn = null;  
  361.         Enumeration enumerate = connections.elements();  
  362.         while (enumerate.hasMoreElements()) {  
  363.             // 得到一个链接对象  
  364.             pConn = (PooledConnection) enumerate.nextElement();  
  365.             // 若是对象忙则等 5 秒 ,5 秒后直接刷新  
  366.             if (pConn.isBusy()) {  
  367.                 wait(5000); // 等 5 秒  
  368.             }  
  369.             // 关闭此链接,用一个新的链接代替它。  
  370.             closeConnection(pConn.getConnection());  
  371.             pConn.setConnection(newConnection());  
  372.             pConn.setBusy(false);  
  373.         }  
  374.     }  
  375.   
  376.     /** 
  377.      * 关闭链接池中全部的链接,并清空链接池。 
  378.      */  
  379.   
  380.     public synchronized void closeConnectionPool() throws SQLException {  
  381.         // 确保链接池存在,若是不存在,返回  
  382.         if (connections == null) {  
  383.             System.out.println(" 链接池不存在,没法关闭 !");  
  384.             return;  
  385.         }  
  386.         PooledConnection pConn = null;  
  387.         Enumeration enumerate = connections.elements();  
  388.         while (enumerate.hasMoreElements()) {  
  389.             pConn = (PooledConnection) enumerate.nextElement();  
  390.             // 若是忙,等 5 秒  
  391.             if (pConn.isBusy()) {  
  392.                 wait(5000); // 等 5 秒  
  393.             }  
  394.             // 5 秒后直接关闭它  
  395.             closeConnection(pConn.getConnection());  
  396.             // 从链接池向量中删除它  
  397.             connections.removeElement(pConn);  
  398.         }  
  399.         // 置链接池为空  
  400.         connections = null;  
  401.     }  
  402.   
  403.     /** 
  404.      * 关闭一个数据库链接 
  405.      *  
  406.      * @param 须要关闭的数据库链接 
  407.      */  
  408.   
  409.     private void closeConnection(Connection conn) {  
  410.         try {  
  411.             conn.close();  
  412.         } catch (SQLException e) {  
  413.             System.out.println(" 关闭数据库链接出错: " + e.getMessage());  
  414.         }  
  415.     }  
  416.     /** 
  417.      * 使程序等待给定的毫秒数 
  418.      *  
  419.      * @param 给定的毫秒数 
  420.      */  
  421.   
  422.     private void wait(int mSeconds) {  
  423.         try {  
  424.             Thread.sleep(mSeconds);  
  425.         } catch (InterruptedException e) {  
  426.         }  
  427.     }  
  428.     /** 
  429.      *  
  430.      * 内部使用的用于保存链接池中链接对象的类 此类中有两个成员,一个是数据库的链接,另外一个是指示此链接是否 正在使用的标志。 
  431.      */  
  432.   
  433.     class PooledConnection {  
  434.         Connection connection = null;// 数据库链接  
  435.         boolean busy = false; // 此链接是否正在使用的标志,默认没有正在使用  
  436.   
  437.         // 构造函数,根据一个 Connection 构告一个 PooledConnection 对象  
  438.         public PooledConnection(Connection connection) {  
  439.             this.connection = connection;  
  440.         }  
  441.   
  442.         // 返回此对象中的链接  
  443.         public Connection getConnection() {  
  444.             return connection;  
  445.         }  
  446.   
  447.         // 设置此对象的,链接  
  448.         public void setConnection(Connection connection) {  
  449.             this.connection = connection;  
  450.         }  
  451.   
  452.         // 得到对象链接是否忙  
  453.         public boolean isBusy() {  
  454.             return busy;  
  455.         }  
  456.   
  457.         // 设置对象的链接正在忙  
  458.         public void setBusy(boolean busy) {  
  459.             this.busy = busy;  
  460.         }  
  461.     }  
  462.   
  463. }  
//////////////////////////////// 数据库链接池类 ConnectionPool.java ////////////////////////////////////////

ConnectionPoolUtils.java

 

 

[java] view plain copy
 
print?
  1. /*链接池工具类,返回惟一的一个数据库链接池对象,单例模式*/  
  2. public class ConnectionPoolUtils {  
  3.     private ConnectionPoolUtils(){};//私有静态方法  
  4.     private static ConnectionPool poolInstance = null;  
  5.     public static ConnectionPool GetPoolInstance(){  
  6.         if(poolInstance == null) {  
  7.             poolInstance = new ConnectionPool(                     
  8.                     "com.mysql.jdbc.Driver",                   
  9.                     "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8",                
  10.                     "root", "123456");  
  11.             try {  
  12.                 poolInstance.createPool();  
  13.             } catch (Exception e) {  
  14.                 // TODO Auto-generated catch block  
  15.                 e.printStackTrace();  
  16.             }  
  17.         }  
  18.         return poolInstance;  
  19.     }  
  20. }  
 
 
ConnectionPoolTest.java

 

 

[java] view plain copy
 
print?
  1. import java.sql.Connection;  
  2. import java.sql.DriverManager;  
  3. import java.sql.ResultSet;  
  4. import java.sql.SQLException;  
  5. import java.sql.Statement;  
  6.   
  7.   
  8. public class ConnectionTest {  
  9.   
  10.     /** 
  11.      * @param args 
  12.      * @throws Exception  
  13.      */  
  14.     public static void main(String[] args) throws Exception {  
  15.          try {  
  16.                   /*使用链接池建立100个链接的时间*/   
  17.                    /*// 建立数据库链接库对象 
  18.                    ConnectionPool connPool = new ConnectionPool("com.mysql.jdbc.Driver","jdbc:mysql://localhost:3306/test", "root", "123456"); 
  19.                    // 新建数据库链接库 
  20.                    connPool.createPool();*/  
  21.                
  22.                   ConnectionPool  connPool=ConnectionPoolUtils.GetPoolInstance();//单例模式建立链接池对象  
  23.                     // SQL测试语句  
  24.                    String sql = "Select * from pet";  
  25.                    // 设定程序运行起始时间  
  26.                    long start = System.currentTimeMillis();  
  27.                          // 循环测试100次数据库链接  
  28.                           for (int i = 0; i < 100; i++) {  
  29.                               Connection conn = connPool.getConnection(); // 从链接库中获取一个可用的链接  
  30.                               Statement stmt = conn.createStatement();  
  31.                               ResultSet rs = stmt.executeQuery(sql);  
  32.                               while (rs.next()) {  
  33.                                   String name = rs.getString("name");  
  34.                                //  System.out.println("查询结果" + name);  
  35.                               }  
  36.                               rs.close();  
  37.                               stmt.close();  
  38.                               connPool.returnConnection(conn);// 链接使用完后释放链接到链接池  
  39.                           }  
  40.                           System.out.println("通过100次的循环调用,使用链接池花费的时间:"+ (System.currentTimeMillis() - start) + "ms");  
  41.                           // connPool.refreshConnections();//刷新数据库链接池中全部链接,即无论链接是否正在运行,都把全部链接都释放并放回到链接池。注意:这个耗时比较大。  
  42.                          connPool.closeConnectionPool();// 关闭数据库链接池。注意:这个耗时比较大。  
  43.                           // 设定程序运行起始时间  
  44.                           start = System.currentTimeMillis();  
  45.                             
  46.                           /*不使用链接池建立100个链接的时间*/  
  47.                          // 导入驱动  
  48.                           Class.forName("com.mysql.jdbc.Driver");  
  49.                           for (int i = 0; i < 100; i++) {  
  50.                               // 建立链接  
  51.                              Connection conn = DriverManager.getConnection(  
  52.                                       "jdbc:mysql://localhost:3306/test", "root", "123456");  
  53.                               Statement stmt = conn.createStatement();  
  54.                               ResultSet rs = stmt.executeQuery(sql);  
  55.                              while (rs.next()) {  
  56.                               }  
  57.                              rs.close();  
  58.                              stmt.close();  
  59.                              conn.close();// 关闭链接  
  60.                          }  
  61.                          System.out.println("通过100次的循环调用,不使用链接池花费的时间:"  
  62.                                  + (System.currentTimeMillis() - start) + "ms");  
  63.                      } catch (SQLException e) {  
  64.                         e.printStackTrace();  
  65.                      } catch (ClassNotFoundException e) {  
  66.                          e.printStackTrace();  
  67.                     }  
  68.     }  
相关文章
相关标签/搜索