package com.dbcp.cn; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.dbcp.BasicDataSourceFactory; import org.junit.Test; public class DBCP_Test { /** * 硬链接 * * @throws Exception */ @Test public void dbcp_test_old() throws Exception { BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl("jdbc:mysql://localhost:3306/staff"); dataSource.setUsername("root"); dataSource.setPassword("123456"); dataSource.setInitialSize(3);// 设置链接池初始值 dataSource.setMaxActive(6);// 设置最大连接数 dataSource.setMaxIdle(3000);// 设置最大活跃时间 dataSource.setDriverClassName("com.mysql.jdbc.Driver"); Connection connection = dataSource.getConnection(); PreparedStatement prepareStatement = connection.prepareStatement("delete from user where id=16"); prepareStatement.executeUpdate(); prepareStatement.close(); connection.close(); } /** * 配置方式实现链接 * @throws Exception */ @Test public void dbcp_test() throws Exception { Properties properties = new Properties();//配置文件 properties.load(DBCP_Test.class.getResourceAsStream("/db.properties")); DataSource dataSource = BasicDataSourceFactory.createDataSource(properties); Connection connection = dataSource.getConnection(); PreparedStatement prepareStatement = connection.prepareStatement("delete from user where id=17"); prepareStatement.executeUpdate(); prepareStatement.close(); connection.close(); } }
url=jdbc:mysql://localhost:3306/staff username=root password=123456 driverClassName=com.mysql.jdbc.Driver
需要导入三个jar包
commons-dbcp-1.4.jar
commons-pool-1.5.6.jar
mysql-connector-java-5.1.7-bin.jar