DBCP连接池
package dbcp; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; import org.junit.Test; // 使用DBCP连接池 public class DBCPTest { public DataSource getDataSource() { // 创建连接对象 BasicDataSource ds = new BasicDataSource(); // 设置连接数据库的四要素 ds.setDriverClassName("com.mysql.cj.jdbc.Driver"); ds.setUrl("jdbc:mysql://localhost:3306/jdbcdemo?useUnicode=true&characterEncoding=utf-8&useSSL=false&&serverTimezone=GMT"); ds.setUsername("root"); ds.setPassword("admin"); ds.setMaxActive(5); // 最大连接数 return ds; } @Test public void test1() throws Exception { DataSource ds = this.getDataSource(); Connection conn = ds.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM t_student"); ResultSet rs = ps.executeQuery(); while(rs.next()) { System.out.println(rs.getLong("id")); } } }