zoukankan      html  css  js  c++  java
  • DataSource

    数据库连接池原理:在内存中开辟一段存储空间用来存储多个Connection连接,避免频繁的创建Connection,从而提高效率。代码如下:

    package jcbc.ds.test1;
    
    
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    import JDBCUtil.JDBCUtil;
    
    import org.junit.Test;
    
    public class JDBCDS1 {
        //List 保存connection
        private static List<Connection> list = new ArrayList<Connection>();
        //获取创建连接
        static{
            try {
                for (int i = 0 ;i < 10; i++){
                    Connection conn =JDBCUtil.getConnection();//再JDBCUtil类中创建了获取连接的方法
                    //存入list中
                    list.add(conn);
                }
                
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        //从连接池中拿出连接(拿出一个连接池就少一个)
        @Test
        public Connection getConnection(){
            return list.remove(0);
        }
        //添加到连接池
        public void releaseConnection(Connection conn){
            list.add(conn); 
        }
    }

    DataSource接口:

    package jcbc.ds.test1;
    
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.sql.SQLFeatureNotSupportedException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.logging.Logger;
    
    import javax.sql.DataSource;
    
    import org.junit.Test;
    
    import JDBCUtil.JDBCUtil;
    
    public class JDBCDS2 implements DataSource {
        
        //实现DataSource 接口
        
        
        
        private static List<Connection> list = new ArrayList<Connection>();
        
        static{
            try {
                for (int i = 0 ;i < 10; i++){
                    Connection conn =JDBCUtil.getConnection();
                    list.add(conn);
                }
                
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        public  Connection getConnection() throws SQLException {
            // TODO Auto-generated method stub
            Connection conn = list.remove(0);
            if(conn != null){
            return conn;
            }
            else {
            throw new RuntimeException("服务器真忙。。。。");    
            }
        }
        public Connection getConnection(String username, String password) throws SQLException {
            
            return null;
            
            
        }
    
        @Override
        public PrintWriter getLogWriter() throws SQLException {
            return null;
        }
    
        @Override
        public void setLogWriter(PrintWriter out) throws SQLException {
    
        }
    
        @Override
        public void setLoginTimeout(int seconds) throws SQLException {
    
        }
    
        @Override
        public int getLoginTimeout() throws SQLException {
            return 0;
        }
    
        @Override
        public Logger getParentLogger() throws SQLFeatureNotSupportedException {
            return null;
        }
    
        @Override
        public <T> T unwrap(Class<T> iface) throws SQLException {
            // TODO Auto-generated method stub
            return null;
        }
    
        @Override
        public boolean isWrapperFor(Class<?> iface) throws SQLException {
            // TODO Auto-generated method stub
            return false;
        }
    
    }
    View Code

     DBCP:

      

    package jcbc.ds.test1;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.util.Properties;
    
    import javax.sql.DataSource;
    
    import org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory;
    
    public class DBCP1 {
    //使用DBCP的步骤:
    //    1.拷jar包:commons-dbcp-1.4.jar,commons-pool-1.5.6.jar
    //    2.将properties文件拷到src目录下
    //    3.改配置文件
        private static DataSource datasource = null;
        static{
            //加载配置文件
            InputStream is =DBCP1.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties pro = new Properties();
            try {
                pro.load(is);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                
                
                //获取datasource
                datasource = BasicDataSourceFactory.createDataSource(pro);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        public static Connection getConnection() throws SQLException{
            //通过datasource获取Connection
            return datasource.getConnection();
        }
        public static DataSource getDataSource(){
            //返回datasource
            return datasource;
        }
        
    
    }

    testDBCP:

    package jcbc.ds.test1;
    
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import org.junit.Test;
    
    import JDBCUtil.JDBCUtil;
    import jcbc.ds.test1.*;
    public class TestDBCP {
        @Test
        public void test() throws SQLException{
            Connection conn = DBCP1.getConnection();
            Statement statement = conn.createStatement();
            
            ResultSet resultset = statement.executeQuery("select * from customers");
            while(resultset.next()){
                System.out.println(resultset.getString("id"));
            }
           conn.close();
            
            
        }
        
    
    }
    aa
    1

    C3P0的使用:

          1.先把c3p0-0.9.5.2.jar和mchange-commons-java-0.2.11.jar两个jar包拷贝到lib目录下

          2.新建类:代码如下(获取Connection类和测试c3p0类)

          

     1 package jcbc.ds.test1;
     2 
     3 import java.beans.PropertyVetoException;
     4 import java.sql.Connection;
     5 import java.sql.SQLException;
     6 
     7 import javax.sql.DataSource;
     8 
     9 import com.mchange.v2.c3p0.ComboPooledDataSource;
    10 
    11 public class C3P0 {
    12     //通过ComboPooledDataSource获取datasource对象
    13     private static ComboPooledDataSource datasource = new ComboPooledDataSource() ;
    14     static{
    15         try {
    16             //在static代码块中获得与数据库的连接
    17             datasource.setDriverClass("com.mysql.jdbc.Driver");
    18             datasource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb1");
    19             datasource.setUser("root");
    20             datasource.setPassword("123456");
    21         } catch (PropertyVetoException e) {
    22             // TODO Auto-generated catch block
    23             e.printStackTrace();
    24         }
    25     }
    26     public static Connection getConnection() throws SQLException{
    27         //返回数据库连接
    28         return datasource.getConnection();
    29     }
    30     public static DataSource getDataSource(){
    31         //返回datasource
    32         return datasource;
    33     }
    34 
    35 }
    c3p0
     1 package jcbc.ds.test1;
     2 
     3 import java.sql.Connection;
     4 import java.sql.ResultSet;
     5 import java.sql.SQLException;
     6 import java.sql.Statement;
     7 import jcbc.ds.test1.*;
     8 
     9 import org.junit.Test;
    10 
    11 public class TestC3p0 {
    12     @Test
    13     public void TestC3p0() throws SQLException{
    14         Connection conn = C3P0.getConnection();
    15         Statement statement = conn.createStatement();
    16         
    17         ResultSet resultset = statement.executeQuery("select * from customers");
    18         while(resultset.next()){
    19             System.out.println(resultset.getDate("date"));
    20         }
    21        conn.close();
    22     }
    23 
    24 }
    testC3p0
     1 九月 09, 2016 8:57:25 下午 com.mchange.v2.log.MLog <clinit>
     2 信息: MLog clients using java 1.4+ standard logging.
     3 九月 09, 2016 8:57:25 下午 com.mchange.v2.c3p0.C3P0Registry banner
     4 信息: Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
     5 九月 09, 2016 8:57:25 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
     6 信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge38g9j462l0p1hqpxz7|311d617d, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge38g9j462l0p1hqpxz7|311d617d, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/mydb1, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
     7 Fri Sep 09 20:57:26 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
     8 Fri Sep 09 20:57:26 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
     9 Fri Sep 09 20:57:26 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    10 1990-09-09
    11 1994-02-09
    result

    C3p0通过配置文件使用:

    写好配置文件后的代码编写

     1 package jcbc.ds.test1;
     2 
     3 import java.sql.Connection;
     4 import java.sql.SQLException;
     5 
     6 import javax.sql.DataSource;
     7 
     8 import com.mchange.v2.c3p0.ComboPooledDataSource;
     9 
    10 public class C3P02 {
    11     private static ComboPooledDataSource datasource = new ComboPooledDataSource();
    12     public static Connection getConnection() throws SQLException{
    13         //通过datasource获取Connection
    14         return datasource.getConnection();
    15     }
    16     public static DataSource getDataSource(){
    17         //返回datasource
    18         return datasource;
    19     }
    20 
    21 }
    c3p0_config
    package jcbc.ds.test1;
    
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import org.junit.Test;
    
    public class TestC3p02 {
        @Test
        public void test() throws SQLException{
            Connection conn = C3P02.getConnection();
            Statement statement = conn.createStatement();
            
            ResultSet resultset = statement.executeQuery("select * from customers");
            while(resultset.next()){
                System.out.println(resultset.getString("id"));
            }
           conn.close();
            
        }
    
    }
    testconfigc3p0
     1 九月 09, 2016 9:17:40 下午 com.mchange.v2.log.MLog <clinit>
     2 信息: MLog clients using java 1.4+ standard logging.
     3 九月 09, 2016 9:17:40 下午 com.mchange.v2.c3p0.C3P0Registry banner
     4 信息: Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
     5 九月 09, 2016 9:17:40 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
     6 信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge38g9j46smme1tkotcn|2f333739, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge38g9j46smme1tkotcn|2f333739, idleConnectionTestPeriod -> 0, initialPoolSize -> 10, jdbcUrl -> jdbc:mysql://localhost:3306/mydb1, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 30, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 100, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 10, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
     7 Fri Sep 09 21:17:41 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
     8 Fri Sep 09 21:17:41 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
     9 Fri Sep 09 21:17:41 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    10 Fri Sep 09 21:17:41 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    11 Fri Sep 09 21:17:41 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    12 aa
    13 1
    result
  • 相关阅读:
    ZMQ面面观
    windows10系统右键新建菜单的自定义
    元组,列表,字典前加*
    HTTP状态码(转)
    字符串利用%02d将月份前加0
    python中while与else的联姻
    sys.argv
    pandas的read_csv踩到的坑
    wireshark抓包总结
    bcolz
  • 原文地址:https://www.cnblogs.com/huxuebing/p/5857449.html
Copyright © 2011-2022 走看看