JDBC【数据库连接池、DbUtils框架、分页】

1.数据库连接池 什么是数据库连接池

简单来说:数据库连接池就是提供连接的。。。

为什么我们要使用数据库连接池

数据库的连接的建立和关闭是非常消耗资源的

频繁地打开、关闭连接造成系统性能低下

编写连接池

编写连接池需实现java.sql.DataSource接口

创建批量的Connection用LinkedList保存【既然是个池,当然用集合保存、、LinkedList底层是链表,对增删性能较好】

实现getConnetion(),让getConnection()每次调用,都是在LinkedList中取一个Connection返回给用户

调用Connection.close()方法,Connction返回给LinkedList

private static LinkedList<Connection> list = new LinkedList<>(); //获取连接只需要一次就够了,所以用static代码块 static { //读取文件配置 InputStream inputStream = Demo1.class.getClassLoader().getResourceAsStream("db.properties"); Properties properties = new Properties(); try { properties.load(inputStream); String url = properties.getProperty("url"); String username = properties.getProperty("username"); String driver = properties.getProperty("driver"); String password = properties.getProperty("password"); //加载驱动 Class.forName(driver); //获取多个连接,保存在LinkedList集合中 for (int i = 0; i < 10; i++) { Connection connection = DriverManager.getConnection(url, username, password); list.add(connection); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } //重写Connection方法,用户获取连接应该从LinkedList中给他 @Override public Connection getConnection() throws SQLException { System.out.println(list.size()); System.out.println(list); //先判断LinkedList是否存在连接 return list.size() > 0 ? list.removeFirst() : null; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyzydp.html