jdbc连接dbcp和c3p0
原创
©著作权归作者所有:来自51CTO博客作者飘火的原创作品,请联系作者获取转载授权,否则将追究法律责任
package dbcp;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp2.BasicDataSource;
import org.junit.Test;
/**
* dbcp
* @author zzh
*
*/
public class Demo {
@Test
public void fun() throws SQLException{
BasicDataSource dataSource =new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/mydb1");
dataSource.setUsername("root");
dataSource.setPassword("123");
dataSource.setMaxWaitMillis(1000);
dataSource.setMinIdle(3);
dataSource.setMaxTotal(20);
Connection con = dataSource.getConnection();
System.out.println(con.getClass().getName());
con.close(); //把连接归还给池
}
}
<pre name="code" class="html"><?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
<default-config>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/test</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>
</c3p0-config>
package c3p0;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* c3p0
* @author zzh
*
*/
public class C3p0Demo {
@Test
public void fun() throws PropertyVetoException, SQLException{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//四大参数
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb1");
dataSource.setUser("root");
dataSource.setPassword("123");
//设置参数
dataSource.setAcquireIncrement(5);
dataSource.setInitialPoolSize(20);
dataSource.setMaxPoolSize(30);
dataSource.setMinPoolSize(2);
Connection con = dataSource.getConnection();
System.out.println(con);
con.close();
}
/**
* 配置文件连接
* 位子:src下 名字:c3p0-cofig.xml
* @throws SQLException
*/
@Test
public void fun2() throws SQLException{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
Connection con = dataSource.getConnection();
System.out.println(con);
con.close();
}
}