JDBC 使用DBCP连接数据库
//Utils
1 public class JdbcUtils_DBCP { 2 private static DataSource dataSource = null; 3 static { 4 try{ 5 InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties"); 6 Properties properties = new Properties(); 7 properties.load(in); 8 9 //创建数据源 工厂模式-》 创建 10 dataSource = BasicDataSourceFactory.createDataSource(properties); 11 12 }catch (Exception e){ 13 e.printStackTrace(); 14 } 15 16 } 17 //获取连接 18 public static Connection getConnection() throws SQLException { 19 return dataSource.getConnection(); 20 } 21 //释放资源 22 public static void release(Connection conn, Statement st, ResultSet rs){ 23 if(rs!=null){ 24 try{ 25 rs.close(); 26 } catch (SQLException e) { 27 e.printStackTrace(); 28 } 29 } 30 if(st!=null){ 31 try { 32 st.close(); 33 } catch (SQLException e) { 34 e.printStackTrace(); 35 } 36 } 37 if(conn!=null){ 38 try { 39 conn.close(); 40 } catch (SQLException e) { 41 e.printStackTrace(); 42 } 43 } 44 45 } 46 }
//测试类
1 public class TestDBCP { 2 public static void main(String[] args) { 3 Connection conn = null; 4 PreparedStatement st = null; 5 ResultSet rs = null; 6 try { 7 conn = JdbcUtils_DBCP.getConnection(); 8 9 String sql = "select * from users where id =?"; 10 11 st = conn.prepareStatement(sql); 12 13 st.setInt(1,1); 14 15 rs = st.executeQuery(); 16 17 if(rs.next()){ 18 System.out.println(rs.getString("name")); 19 } 20 } catch (SQLException e) { 21 e.printStackTrace(); 22 }finally { 23 JdbcUtils.release(conn,st,rs); 24 } 25 } 26 }
//dbcpconfig.properties
1 #驱动名 2 driverClassName=com.mysql.cj.jdbc.Driver 3 #url 4 url=url=jdbc:mysql://localhost:3306/jdbcstudy?serverTimezone=GMT%2B8 5 #用户名 6 username=root 7 #密码 8 password=123456789 9 #初试连接数 10 initialSize=30 11 #最大活跃数 12 maxTotal=30 13 #最大idle数 14 maxIdle=10 15 #最小idle数 16 minIdle=5 17 #最长等待时间(毫秒) 18 maxWaitMillis=1000 19 #程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow) 20 #removeAbandoned=true 21 removeAbandonedOnMaintenance=true 22 removeAbandonedOnBorrow=true 23 #连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒) 24 removeAbandonedTimeout=1