package dbcp; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.Properties; import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; public class DruidUtil { private static DataSource ds = null; static { try { Properties p = new Properties(); p.load(Thread.currentThread().getContextClassLoader() .getResourceAsStream("druid.properties")); // 创建DataSource对象 ds = DruidDataSourceFactory.createDataSource(p); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConn() { try { return ds.getConnection(); } catch (Exception e) { e.printStackTrace(); } return null; } public static void close(Connection conn, Statement st, ResultSet rs) { try { if(rs != null) { rs.close(); } } catch (Exception e) { } finally { try { if(st != null) { st.close(); } } catch (Exception e2) { } finally { try { if(conn != null) { conn.close(); } } catch (Exception e3) { } } } } }
测试:
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(); Connection conn = DruidUtil.getConn(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM t_student"); ResultSet rs = ps.executeQuery(); while(rs.next()) { System.out.println(rs.getLong("id")); } } }
配置文件
driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/jdbcdemo?useUnicode=true&characterEncoding=utf-8&useSSL=false&&serverTimezone=GMT username=root password=admin maxActive=10 validationQuery:SELECT 1 testWhileIdle:true testOnBorrow:false testOnReturn:false