袁艺

个人站

欢迎来到我的个人站~


JDBC连接池

概述

用池来管理connection,这样可以重复使用connection。可以通过池来获取connection对象,使用完connection之后,调用close方法,“归还”给池。方便下次调用。

规范

常见的连接池:DBCP、C3P0

DBCP(DataBase connection pool),数据库连接池。是 apache 上的一个 java 连接池项目,也是 tomcat 使用的连接池组件。单独使用dbcp需要2个包:commons-dbcp.jar,commons-pool.jar由于建立数据库连接是一个非常耗时耗资源的行为,所以通过连接池预先同数据库建立一些连接,放在内存中,应用程序需要建立数据库连接时直接到连接池中申请一个就行,用完后再放回去。tomcat内置的连接池

C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目有Hibernate,Spring等。

C3P0

  • 导入jar包jar

  • 配置文件

  • 名称:c3p0-config.xml

  • 位置:src(类路径)

    • 配置文件内容

      <?xml version="1.0" encoding="UTF-8"?>
      <c3p0-config>
      <!--默认的配置-->
        <default-config>
          <property name="driverClass">com.mysql.jdbc.Driver</property>
      	<property name="jdbcUrl">jdbc:mysql:///web_07</property>
      	<property name="user">root</property>
      	<property name="password">123</property>
      	<property name="initialPoolSize">5</property>
      	<property name="maxPoolSize">20</property>
        </default-config>
        <!--命名的配置-->
        <named-config name="oracle"> 
          <property name="driverClass">com.mysql.jdbc.Driver</property>
      	<property name="jdbcUrl">jdbc:mysql:///web_07</property>
      	<property name="user">root</property>
      	<property name="password">123</property>
        </named-config>
      </c3p0-config>
      
  • 常见的配置项

  • 编写工具类 核心工具类:ComboPooledDataSource

    • new ComboPooledDataSource(“名称”)
    • new ComboPooledDataSource()
    public class JDBCUtils2 {
    	//使用默认配置
    	private static  ComboPooledDataSource dataSource =new ComboPooledDataSource();
    	//使用命名配置
    	private static  ComboPooledDataSource dataSource =new ComboPooledDataSource(oracle);
    	//获取数据源(连接池)
    	public static DataSource getDataSource(){
    		return dataSource
    	}
    	/**
    	 * 获得连接的方法
    	 */
    	public static Connection getConnection(){
    		Connection conn = null;
    		try {
    			conn = DATA_SOURCE.getConnection();
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return conn;
    	}
    ...
    

DBCP

  • 导jar包jar

  • 配置文件

    • 名称:*.properties

    • 位置:任意,建议src

    • 配置文件内容:不能编写中文 ​

      #连接设置
      driverClassName=com.mysql.jdbc.Driver
      url=jdbc:mysql://localhost:3306/jdbc
      username=root
      password=
      
      #<!-- 初始化连接 -->
      initialSize=10
      
      #最大连接数量
      maxActive=50
      
      #<!-- 最大空闲连接 -->
      maxIdle=20
      
      #<!-- 最小空闲连接 -->
      minIdle=5
      
      #<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
      maxWait=60000
      

      #JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] #注意:”user” 与 “password” 两个属性会被明确地传递,因此这里不需要包含他们。 connectionProperties=useUnicode=true;characterEncoding=gbk

      #指定由连接池所创建的连接的自动提交(auto-commit)状态。 defaultAutoCommit=true

      #driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。 #可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE defaultTransactionIsolation=READ_UNCOMMITTED ​```

  • 常见配置项

  • 编写工具类 ​

    public class DBCPUtils {
    	private static DataSource dataSource;
    	static{
    		try {
    			//1.加载找properties文件输入流
    			InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
    			//2.加载输入流
    			Properties props = new Properties();
    			props.load(is);
    			//3.创建数据源
    			dataSource = BasicDataSourceFactory.createDataSource(props);
    		} catch (Exception e) {
    			throw new RuntimeException(e);
    		}
    	}
        	
    	public static DataSource getDataSource(){
    		return dataSource;
    	}
        	
    	public static Connection getConnection(){
    		try {
    			return dataSource.getConnection();
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    }
    
    
    • 测试类
    @Test
    	/**
    	 * 手动方式:
    	 */
    	public void demo1(){
    		Connection conn = null;
    		PreparedStatement stmt = null;
    		ResultSet rs = null;
    		BasicDataSource dataSource = new BasicDataSource();
    		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    		dataSource.setUrl("jdbc:mysql:///web_07");
    		dataSource.setUsername("root");
    		dataSource.setPassword("123");
    		try{
    			// 获得连接:
    			conn = dataSource.getConnection();
    			// 编写SQL:
    			String sql = "select * from category";
    			// 预编译SQL:
    			stmt = conn.prepareStatement(sql);
    			// 执行SQL:
    			rs = stmt.executeQuery();
    			while(rs.next()){
    				System.out.println(rs.getInt("cid")+"   "+rs.getString("cname"));
    			}
    		}catch(Exception e){
    			e.printStackTrace();
    		}finally{
    			JDBCUtils.release(rs,stmt, conn);
    		}
    	}
        	
    	@Test
    	/**
    	 * 配置文件方式:
    	 */
    	public void demo2(){
    		Connection conn = null;
    		PreparedStatement stmt = null;
    		ResultSet rs = null;
    		Properties properties = new Properties();
        		
    		try{
    			properties.load(new FileInputStream("src/dbcpconfig.properties"));
    			DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
    			// 获得连接:
    			conn = dataSource.getConnection();
    			// 编写SQL:
    			String sql = "select * from category";
    			// 预编译SQL:
    			stmt = conn.prepareStatement(sql);
    			// 执行SQL:
    			rs = stmt.executeQuery();
    			while(rs.next()){
    				System.out.println(rs.getInt("cid")+"   "+rs.getString("cname"));
    			}
    		}catch(Exception e){
    			e.printStackTrace();
    		}finally{
    			JDBCUtils.release(rs,stmt, conn);
    		}
    	}