zoukankan      html  css  js  c++  java
  • Java数据库连接池实现原理

     

     
    一般来说,Java应用程序访问数据库的过程是:
      ①装载数据库驱动程序;
      ②通过jdbc建立数据库连接;
      ③访问数据库,执行sql语句;

      ④断开数据库连接。

    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.             }   
    
    
    

                         

    程序开发过程中,存在很多问题:

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

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

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

    ConnectionPool.java

    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
    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
    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.     }  
    
    
     
     
  • 相关阅读:
    extern "C" 分析 转
    Python标准库3.4.3webbrowser21.1
    rxtx java lib /var/lock issue
    list installed package & remove installed package & find package from repository Archlinux
    eclipse initialize
    add repo for CentOS
    RPMforge for CentOS
    Install Core Development Tools
    [Qtcreator] CMake + Multiple Build configuration
    list installed package & remove installed package & find package from repository
  • 原文地址:https://www.cnblogs.com/devin-ou/p/7989701.html
Copyright © 2011-2022 走看看