c3p0的使用

   我们在使用数据库连接时候,很多时候会考虑使用数据库连接池,因为数据库连接池的机制,使得在大用户数量上进行交互的时候使得其效率比较有优势!

http://blog.csdn.net/eclipser1987/article/details/5181320

[java]  view plain copy
  1. public class DBPool {  
  2.     private static DBPool dbPool;  
  3.     private ComboPooledDataSource dataSource;  
  4.   
  5.     static {  
  6.         dbPool = new DBPool();  
  7.     }  
  8.   
  9.     public DBPool() {  
  10.         try {  
  11.             dataSource = new ComboPooledDataSource();  
  12.             dataSource.setUser("root");  
  13.             dataSource.setPassword("123456");  
  14.             dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/game?user=root&password=123456&useUnicode=true");  
  15.             dataSource.setDriverClass("com.mysql.jdbc.Driver");  
  16.             // 设置初始连接池的大小!  
  17.             dataSource.setInitialPoolSize(2);  
  18.             // 设置连接池的最小值!   
  19.             dataSource.setMinPoolSize(1);  
  20.             // 设置连接池的最大值!   
  21.             dataSource.setMaxPoolSize(10);  
  22.             // 设置连接池中的最大Statements数量!  
  23.             dataSource.setMaxStatements(50);  
  24.             // 设置连接池的最大空闲时间!  
  25.             dataSource.setMaxIdleTime(60);  
  26.         } catch (PropertyVetoException e) {  
  27.             throw new RuntimeException(e);  
  28.         }  
  29.     }  
  30.   
  31.     public final static DBPool getInstance() {  
  32.         return dbPool;  
  33.     }  
  34.   
  35.     public final Connection getConnection() {  
  36.         try {  
  37.             return dataSource.getConnection();  
  38.         } catch (SQLException e) {  
  39.             throw new RuntimeException("无法从数据源获取连接 ", e);  
  40.         }  
  41.     }  
  42.   
  43.     public static void main(String[] args) throws SQLException {  
  44.         Connection con = null;  
  45.         try {  
  46.             con = DBPool.getInstance().getConnection();  
  47.             ResultSet rs = con.createStatement().executeQuery("SELECT * FROM LESOGO_USER");  
  48.             while (rs.next()) {  
  49.                 System.out.println(rs.getObject(1));  
  50.                 System.out.println(rs.getObject(2));  
  51.                 System.out.println(rs.getObject(3));  
  52.             }  
  53.         } catch (Exception e) {  
  54.         } finally {  
  55.             if (con != null)  
  56.                 con.close();  
  57.         }  
  58.     }  
  59. }  

 

[java]  view plain copy
  1. /** 
  2.  * 此示例演示如何获得C3P0的数据源并将其绑定到一个JNDI名称服务。 
  3.  */  
  4. public final class JndiBindDataSource {  
  5.     /** 
  6.      * 一定要载入数据库驱动程序类,要么通过Class.forName()[如下]或外部显示(例如,通过使用- Djdbc.drivers启动时你的JVM)。 
  7.      */  
  8.     static {  
  9.         try {  
  10.             Class.forName("com.mysql.jdbc.Driver");  
  11.         } catch (Exception e) {  
  12.             e.printStackTrace();  
  13.         }  
  14.     }  
  15.   
  16.     public static void main(String[] argv) {  
  17.         try {  
  18.             /** 
  19.              * 让一个命令行参数指定名称,将我们的数据源的绑定。 
  20.              */  
  21.             String jndiName = argv[0];  
  22.             /** 
  23.              * 获取数据源使用预设池params ... 
  24.              * 这是唯一的C3P0的特定代码在这里 
  25.              */  
  26.             DataSource unpooled = DataSources  
  27.                     .unpooledDataSource("jdbc:mysql://127.0.0.1:3306/game?user=root&password=123456&useUnicode=true""root""123456");  
  28.             DataSource pooled = DataSources.pooledDataSource(unpooled);  
  29.             System.out.println("是否能够获得Connection : "+pooled.getConnection());  
  30.               
  31.             /** 
  32.              * 创建的InitialContext,并绑定的数据源,以它在通常的方式。 
  33.              * 我们使用的是没有的的InitialContext的构造参数版本,因此通过jndi.properties的文件, 
  34.              * 系统属性,或通过其他手段,JNDI环境,必须先设置。 
  35.              */  
  36.             InitialContext ctx = new InitialContext();  
  37.             System.out.println("jndiName : " + jndiName);  
  38.             ctx.rebind(jndiName, pooled);  
  39.             System.out.println("DataSource bound to nameservice under the name /"" + jndiName + '/"');  
  40.         } catch (Exception e) {  
  41.             e.printStackTrace();  
  42.         }  
  43.     }  
  44.   
  45.     static void attemptClose(ResultSet o) {  
  46.         try {  
  47.             if (o != null)  
  48.                 o.close();  
  49.         } catch (Exception e) {  
  50.             e.printStackTrace();  
  51.         }  
  52.     }  
  53.   
  54.     static void attemptClose(Statement o) {  
  55.         try {  
  56.             if (o != null)  
  57.                 o.close();  
  58.         } catch (Exception e) {  
  59.             e.printStackTrace();  
  60.         }  
  61.     }  
  62.   
  63.     static void attemptClose(Connection o) {  
  64.         try {  
  65.             if (o != null)  
  66.                 o.close();  
  67.         } catch (Exception e) {  
  68.             e.printStackTrace();  
  69.         }  
  70.     }  
  71.   
  72.     private JndiBindDataSource() {  
  73.     }  
  74. }  

 

[java]  view plain copy
  1. /** 
  2.  * 此示例演示如何以编程方式,直接使用unpooled数据源 
  3.  */  
  4. public final class UseJndiDataSource {  
  5.   
  6.     public static void main(String[] argv) {  
  7.         try {  
  8.             /** 
  9.              * 让一个命令行参数指定名称,我们将查找的数据源。 
  10.              */  
  11.             String jndiName = argv[0];  
  12.   
  13.             /** 
  14.              * 创建InitialContext的,和查找惯常做法的DataSource。 我们使用的是没有的的InitialContext的构造参数版本,因此通过jndi.properties的文件, 
  15.              * 系统属性,或通过其他手段,JNDI环境,必须先设置。 
  16.              */  
  17.             InitialContext ctx = new InitialContext();  
  18.   
  19.             /** 
  20.              * 获取数据源...这是唯一的C3P0的特定代码在这里 
  21.              */  
  22.             DataSource ds = (DataSource) ctx.lookup(jndiName);  
  23.   
  24.             /** 
  25.              * 掌握了这样一个连接东西,通常的方式 
  26.              */  
  27.             Connection con = null;  
  28.             Statement stmt = null;  
  29.             ResultSet rs = null;  
  30.             try {  
  31.                 con = ds.getConnection();  
  32.                 stmt = con.createStatement();  
  33.                 rs = stmt.executeQuery("SELECT * FROM LESOGO_USER");  
  34.                 while (rs.next())  
  35.                     System.out.println(rs.getString(1));  
  36.             } finally {  
  37.                 /** 
  38.                  * 我试图约在资源管理,`神经质显式关闭每个资源,但如果你只收盘家长资源的习惯(如连接), 让他们接近自己的孩子,都C3P0的数据源一定会妥善处理。 
  39.                  */  
  40.                 attemptClose(rs);  
  41.                 attemptClose(stmt);  
  42.                 attemptClose(con);  
  43.             }  
  44.         } catch (Exception e) {  
  45.             e.printStackTrace();  
  46.         }  
  47.     }  
  48.   
  49.     static void attemptClose(ResultSet o) {  
  50.         try {  
  51.             if (o != null)  
  52.                 o.close();  
  53.         } catch (Exception e) {  
  54.             e.printStackTrace();  
  55.         }  
  56.     }  
  57.   
  58.     static void attemptClose(Statement o) {  
  59.         try {  
  60.             if (o != null)  
  61.                 o.close();  
  62.         } catch (Exception e) {  
  63.             e.printStackTrace();  
  64.         }  
  65.     }  
  66.   
  67.     static void attemptClose(Connection o) {  
  68.         try {  
  69.             if (o != null)  
  70.                 o.close();  
  71.         } catch (Exception e) {  
  72.             e.printStackTrace();  
  73.         }  
  74.     }  
  75.   
  76.     private UseJndiDataSource() {  
  77.     }  
  78. }  

 

[java]  view plain copy
  1. /** 
  2.  * 此示例演示如何以编程方式,直接使用数据库连接池中的数据源 
  3.  */  
  4. public final class UsePoolBackedDataSource {  
  5.   
  6.     public static void main(String[] argv) {  
  7.         try {  
  8.             //  
  9.             // 收购之前,您的数据源!  
  10.   
  11.             // 获取数据源...这是唯一的C3P0的特定代码在这里  
  12.             DataSource unpooled = DataSources.unpooledDataSource(  
  13.                     "jdbc:mysql://127.0.0.1:3306/lesogo_game2?user=root&password=123456&useUnicode=true""root",  
  14.                     "123456");  
  15.             DataSource pooled = DataSources.pooledDataSource(unpooled);  
  16.   
  17.             Connection con = null;  
  18.             Statement stmt = null;  
  19.             ResultSet rs = null;  
  20.             try {  
  21.                 con = pooled.getConnection();  
  22.                 stmt = con.createStatement();  
  23.                 rs = stmt.executeQuery("SELECT * FROM LESOGO_USER");  
  24.                 while (rs.next())  
  25.                     System.out.println(rs.getString(1));  
  26.             } finally {  
  27.                 attemptClose(rs);  
  28.                 attemptClose(stmt);  
  29.                 attemptClose(con);  
  30.             }  
  31.         } catch (Exception e) {  
  32.             e.printStackTrace();  
  33.         }  
  34.     }  
  35.   
  36.     static void attemptClose(ResultSet o) {  
  37.         try {  
  38.             if (o != null)  
  39.                 o.close();  
  40.         } catch (Exception e) {  
  41.             e.printStackTrace();  
  42.         }  
  43.     }  
  44.   
  45.     static void attemptClose(Statement o) {  
  46.         try {  
  47.             if (o != null)  
  48.                 o.close();  
  49.         } catch (Exception e) {  
  50.             e.printStackTrace();  
  51.         }  
  52.     }  
  53.   
  54.     static void attemptClose(Connection o) {  
  55.         try {  
  56.             if (o != null)  
  57.                 o.close();  
  58.         } catch (Exception e) {  
  59.             e.printStackTrace();  
  60.         }  
  61.     }  
  62.   
  63.     private UsePoolBackedDataSource() {  
  64.     }  
  65. }  






从网上看到的一个关于数据库连接在使用了C3P0前后的比较。本人暂时还没有测试过。

 

下面是一个C3P0的工具类。

Java代码 复制代码  收藏代码
  1. import java.beans.PropertyVetoException;   
  2. import java.sql.Connection;   
  3. import java.sql.SQLException;   
  4. import com.mchange.v2.c3p0.ComboPooledDataSource;   
  5.   
  6. public final class ConnectionManager {   
  7.   
  8.     private static ConnectionManager instance;   
  9.     private static ComboPooledDataSource dataSource;   
  10.   
  11.     private ConnectionManager() throws SQLException, PropertyVetoException {   
  12.         dataSource = new ComboPooledDataSource();   
  13.   
  14.         dataSource.setUser("loux");   
  15.         dataSource.setPassword("loux");   
  16.         dataSource.setJdbcUrl("jdbc:oracle:thin:@192.168.100.70:1521:orcl");   
  17.         dataSource.setDriverClass("oracle.jdbc.driver.OracleDriver");   
  18.         dataSource.setInitialPoolSize(5);   
  19.         dataSource.setMinPoolSize(1);   
  20.         dataSource.setMaxPoolSize(10);   
  21.         dataSource.setMaxStatements(50);   
  22.         dataSource.setMaxIdleTime(60);   
  23.     }   
  24.   
  25.     public static final ConnectionManager getInstance() {   
  26.         if (instance == null) {   
  27.             try {   
  28.                 instance = new ConnectionManager();   
  29.             } catch (Exception e) {   
  30.                 e.printStackTrace();   
  31.             }   
  32.         }   
  33.         return instance;   
  34.     }   
  35.   
  36.     public synchronized final Connection getConnection() {   
  37.         Connection conn = null;   
  38.         try {   
  39.             conn = dataSource.getConnection();   
  40.         } catch (SQLException e) {   
  41.             e.printStackTrace();   
  42.         }   
  43.         return conn;   
  44.     }   
  45. }  
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public final class ConnectionManager {

    private static ConnectionManager instance;
    private static ComboPooledDataSource dataSource;

    private ConnectionManager() throws SQLException, PropertyVetoException {
        dataSource = new ComboPooledDataSource();

        dataSource.setUser("loux");
        dataSource.setPassword("loux");
        dataSource.setJdbcUrl("jdbc:oracle:thin:@192.168.100.70:1521:orcl");
        dataSource.setDriverClass("oracle.jdbc.driver.OracleDriver");
        dataSource.setInitialPoolSize(5);
        dataSource.setMinPoolSize(1);
        dataSource.setMaxPoolSize(10);
        dataSource.setMaxStatements(50);
        dataSource.setMaxIdleTime(60);
    }

    public static final ConnectionManager getInstance() {
        if (instance == null) {
            try {
                instance = new ConnectionManager();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return instance;
    }

    public synchronized final Connection getConnection() {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}

 接下来是数据库使用了c3p0连接池和没有使用c3p0的连接操作。

Java代码 复制代码  收藏代码
  1. import java.sql.Connection;   
  2. import java.sql.PreparedStatement;   
  3. import java.sql.ResultSet;   
  4. import java.sql.SQLException;   
  5.   
  6. import oracle.jdbc.pool.OracleDataSource;   
  7.   
  8. public class ConnectionDemo {   
  9.   
  10.     public static void main(String[] args) throws SQLException {   
  11.         System.out.println("使用连接池................................");   
  12.         for (int i = 0; i < 20; i++) {   
  13.             long beginTime = System.currentTimeMillis();   
  14.             Connection conn = ConnectionManager.getInstance().getConnection();   
  15.             try {   
  16.                 PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM t_fmscpy200");   
  17.                 ResultSet rs = pstmt.executeQuery();   
  18.                 while (rs.next()) {   
  19.                 }   
  20.             } catch (SQLException e) {   
  21.                 e.printStackTrace();   
  22.             } finally {   
  23.                 try {   
  24.                     conn.close();   
  25.                 } catch (SQLException e) {   
  26.                     e.printStackTrace();   
  27.                 }   
  28.             }   
  29.   
  30.             long endTime = System.currentTimeMillis();   
  31.             System.out.println("第" + (i + 1) + "次执行花费时间为:" + (endTime - beginTime));   
  32.         }   
  33.   
  34.         System.out.println("不使用连接池................................");   
  35.         for (int i = 0; i < 20; i++) {   
  36.             long beginTime = System.currentTimeMillis();   
  37.             OracleDataSource ods = new OracleDataSource();   
  38.             ods.setUser("loux");   
  39.             ods.setPassword("loux");   
  40.             ods.setURL("jdbc:oracle:thin:@192.168.100.70:1521:orcl");   
  41.             Connection conn = ods.getConnection();   
  42.             try {   
  43.                 PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM table_name");   
  44.                 ResultSet rs = pstmt.executeQuery();   
  45.                 while (rs.next()) {   
  46.                                     // do nothing...   
  47.                 }   
  48.             } catch (SQLException e) {   
  49.                 e.printStackTrace();   
  50.             } finally {   
  51.                 try {   
  52.                     conn.close();   
  53.                 } catch (SQLException e) {   
  54.                     e.printStackTrace();   
  55.                 }   
  56.             }   
  57.             long endTime = System.currentTimeMillis();   
  58.             System.out.println("第" + (i + 1) + "次执行花费时间为:"  
  59.                                 + (endTime - beginTime));   
  60.         }   
  61.   
  62.     }   
  63. }  
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import oracle.jdbc.pool.OracleDataSource;

public class ConnectionDemo {

    public static void main(String[] args) throws SQLException {
        System.out.println("使用连接池................................");
        for (int i = 0; i < 20; i++) {
            long beginTime = System.currentTimeMillis();
            Connection conn = ConnectionManager.getInstance().getConnection();
            try {
                PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM t_fmscpy200");
                ResultSet rs = pstmt.executeQuery();
                while (rs.next()) {
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            long endTime = System.currentTimeMillis();
            System.out.println("第" + (i + 1) + "次执行花费时间为:" + (endTime - beginTime));
        }

        System.out.println("不使用连接池................................");
        for (int i = 0; i < 20; i++) {
            long beginTime = System.currentTimeMillis();
            OracleDataSource ods = new OracleDataSource();
            ods.setUser("loux");
            ods.setPassword("loux");
            ods.setURL("jdbc:oracle:thin:@192.168.100.70:1521:orcl");
            Connection conn = ods.getConnection();
            try {
                PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM table_name");
                ResultSet rs = pstmt.executeQuery();
                while (rs.next()) {
                                    // do nothing...
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            long endTime = System.currentTimeMillis();
            System.out.println("第" + (i + 1) + "次执行花费时间为:"
                                + (endTime - beginTime));
        }

    }
}

 最后是控制台输出:

控制台输出代码 复制代码  收藏代码
  1. 使用连接池................................    
  2. 1次执行花费时间为:1469    
  3. 2次执行花费时间为:0    
  4. 3次执行花费时间为:16    
  5. 4次执行花费时间为:0    
  6. 5次执行花费时间为:0    
  7. 6次执行花费时间为:15    
  8. 7次执行花费时间为:0    
  9. 8次执行花费时间为:0    
  10. 9次执行花费时间为:0    
  11. 10次执行花费时间为:0    
  12. 11次执行花费时间为:16    
  13. 12次执行花费时间为:0    
  14. 13次执行花费时间为:0    
  15. 14次执行花费时间为:0    
  16. 15次执行花费时间为:0    
  17. 16次执行花费时间为:16    
  18. 17次执行花费时间为:0    
  19. 18次执行花费时间为:0    
  20. 19次执行花费时间为:15    
  21. 20次执行花费时间为:0    
  22. 不使用连接池................................    
  23. 1次执行花费时间为:47    
  24. 2次执行花费时间为:31    
  25. 3次执行花费时间为:32    
  26. 4次执行花费时间为:46    
  27. 5次执行花费时间为:32    
  28. 6次执行花费时间为:31    
  29. 7次执行花费时间为:47    
  30. 8次执行花费时间为:31    
  31. 9次执行花费时间为:47    
  32. 10次执行花费时间为:31    
  33. 11次执行花费时间为:47    
  34. 12次执行花费时间为:31    
  35. 13次执行花费时间为:32    
  36. 14次执行花费时间为:46    
  37. 15次执行花费时间为:47    
  38. 16次执行花费时间为:32    
  39. 17次执行花费时间为:46    
  40. 18次执行花费时间为:47    
  41. 19次执行花费时间为:32    
  42. 20次执行花费时间为:31  
可以看出,在使用连接池时,第一次执行花费的时间稍长,因为第一次初始化操作需要创建多个连接并放入池中,以后使用时将会大大缩短执行时间。 

在不使用连接池时,每次花费的时间都比较长。

 

转载于:http://topic.csdn.net/u/20070702/21/82749d1e-0746-415e-b7da-1ddfb3c885f5.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

福海鑫森

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值