1 try{ 2 //1.创建Druid数据源对象 3 DruidDataSource dataSource = new DruidDataSource(); 4 5 //2.设置数据库连接信息 6 dataSource.setDriverClassName("com.mysql.jdbc.Driver"); 7 dataSource.setUrl("jdbc:mysql://localhost:3306/dbtao?useSSL=false"); 8 dataSource.setUsername("root"); 9 dataSource.setPassword(""); 10 //设置连接池初始化的连接个数 11 dataSource.setInitialSize(5); 12 13 //3.从数据库连接池获取数据库连接 14 // 首次从连接池获取连接时,会初始化话连接池中的连接数 15 Connection conn = dataSource.getConnection(); 16 PreparedStatement st = conn.prepareStatement("select * from emp"); 17 ResultSet rs = st.executeQuery(); 18 while(rs.next()){ 19 System.out.println(rs.getString("ename")); 20 } 21 rs.close(); 22 st.close(); 23 //4.释放数据库连接,不是关闭数据库连接,而是放回了数据库连接池中 24 conn.close(); 25 //5.关闭数据源 26 dataSource.close(); 27 }catch(Exception e){ 28 e.getStackTrace(); 29 }
原文:https://www.cnblogs.com/AardWolf/p/10944917.html