使用DBCP便利链接数据库以及使用链接池
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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步