Java數據庫連接池實現原理


 

 
一般來說,Java應用程序訪問數據庫的過程是:
  ①裝載數據庫驅動程序;
  ②通過jdbc建立數據庫連接;
  ③訪問數據庫,執行sql語句;

  ④斷開數據庫連接。

 

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

 

                     

 

程序開發過程中,存在很多問題:

首先,每一次web請求都要建立一次數據庫連接。建立連接是一個費時的活動,每次都得花費0.05s~1s的時間,而且系統還要分配內存資源。這個時間對於一次或幾次數據庫操作,或許感覺不出系統有多大的開銷。

可是對於現在的web應用,尤其是大型電子商務網站,同時有幾百人甚至幾千人在線是很正常的事。在這種情況下,頻繁的進行數據庫連接操作勢必占用很多的系統資源,網站的響應速度必定下降,嚴重的甚至會造成服務器的崩潰。不是危言聳聽,這就是制約某些電子商務網站發展的技術瓶頸問題。其次,對於每一次數據庫連接,使用完后都得斷開。否則,如果程序出現異常而未能關閉,將會導致數據庫系統中的內存泄漏,最終將不得不重啟數據庫

     通過上面的分析,我們可以看出來,“數據庫連接”是一種稀缺的資源,為了保障網站的正常使用,應該對其進行妥善管理。實現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.     }  

 

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM