C3P0的使用

第一种方式,无配置

public static void main(String[] args) {
		
		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			ComboPooledDataSource dataSource = new ComboPooledDataSource();
			dataSource.setDriverClass("oracle.jdbc.OracleDriver");
			dataSource.setJdbcUrl("jdbc:oracle:thin:@172.18.9.24:1521:orcl");
			dataSource.setUser("scott");
			dataSource.setPassword("tiger");
		    conn = dataSource.getConnection();
		    String sql = "select * from emp20";
		    pstm = conn.prepareStatement(sql);
		    rs = pstm.executeQuery();
		    while(rs.next()){
		    	System.out.println(rs.getString("ename"));
		    }
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			//释放资源
		}
	}

第二种方式,配置实现

public static void main(String[] args) {
		
		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			//默认加载c3p0-config.xml  (类加载路径)
			ComboPooledDataSource dataSource = new ComboPooledDataSource();
		    conn = dataSource.getConnection();
		    String sql = "select * from emp20";
		    pstm = conn.prepareStatement(sql);
		    rs = pstm.executeQuery();
		    while(rs.next()){
		    	System.out.println(rs.getString("ename"));
		    }
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			//释放资源
		}
	}

默认加载类路径下的配置文件c3p0-config.xml,

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>

	<!-- default-config 默认的配置,  -->
  <default-config>
    <property name="driverClass">oracle.jdbc.OracleDriver</property>
    <property name="jdbcUrl">jdbc:oracle:thin:@172.18.9.24:1521:orcl</property>
    <property name="user">scott</property>
    <property name="password">tiger</property>
    
    
    <property name="initialPoolSize">10</property>
    <property name="maxIdleTime">30</property>
    <property name="maxPoolSize">100</property>
    <property name="minPoolSize">10</property>
    <property name="maxStatements">200</property>
  </default-config>
  
   <!-- This app is massive! -->
  <named-config name="oracle"> 
    <property name="acquireIncrement">50</property>
    <property name="initialPoolSize">100</property>
    <property name="minPoolSize">50</property>
    <property name="maxPoolSize">1000</property>

    <!-- intergalactoApp adopts a different approach to configuring statement caching -->
    <property name="maxStatements">0</property> 
    <property name="maxStatementsPerConnection">5</property>

    <!-- he's important, but there's only one of him -->
    <user-overrides user="master-of-the-universe"> 
      <property name="acquireIncrement">1</property>
      <property name="initialPoolSize">1</property>
      <property name="minPoolSize">1</property>
      <property name="maxPoolSize">5</property>
      <property name="maxStatementsPerConnection">50</property>
    </user-overrides>
  </named-config>

 
</c3p0-config>
	

猜你喜欢

转载自blog.csdn.net/xldmx/article/details/84252797
今日推荐