首页 > 代码库 > Java web----C3P0

Java web----C3P0

1 C3P0简介

C3P0也是开源免费的连接池!C3P0被很多人看好!

2 C3P0的使用

package com.cug.c3p0;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import org.junit.Test;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Demo {
	@Test
	public void fun1() throws PropertyVetoException, SQLException{
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		
		dataSource.setUser("root");
		dataSource.setPassword("123");
		dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb1");
		dataSource.setDriverClass("com.mysql.jdbc.Driver");
		
		dataSource.setMaxPoolSize(30);
		dataSource.setMinPoolSize(10);
		dataSource.setInitialPoolSize(10);
		dataSource.setMaxIdleTime(3000);
		dataSource.setAcquireIncrement(5);
		
		Connection conn = dataSource.getConnection();
		//com.mchange.v2.c3p0.impl.NewProxyConnection@d8d25de
		System.out.println(conn);
		conn.close();
	}
}

配置文件要求:

  • 文件名称:必须叫c3p0-config.xml
  • 文件位置:必须在src下

c3p0也可以指定配置文件,而且配置文件可以是properties,也可骒xml的。当然xml的高级一些了。但是c3p0的配置文件名必须为c3p0-config.xml,并且必须放在类路径下。

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb1</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="user">root</property>
		<property name="password">123</property>
		<property name="acquireIncrement">3</property>
		<property name="initialPoolSize">10</property>
		<property name="minPoolSize">2</property>
		<property name="maxPoolSize">10</property>
	</default-config>
	<named-config name="oracle-config">
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb1</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="user">root</property>
		<property name="password">123</property>
		<property name="acquireIncrement">3</property>
		<property name="initialPoolSize">10</property>
		<property name="minPoolSize">2</property>
		<property name="maxPoolSize">10</property>
	</named-config>
</c3p0-config>

	public void fun2() throws PropertyVetoException, SQLException {
		ComboPooledDataSource ds = new ComboPooledDataSource();
		Connection con = ds.getConnection();
		System.out.println(con);
		con.close();
	}
	public void fun2() throws PropertyVetoException, SQLException {
		ComboPooledDataSource ds = new ComboPooledDataSource("orcale-config");
		Connection con = ds.getConnection();
		System.out.println(con);
		con.close();
	}




Java web----C3P0