1. 在内存中开辟一块空间,存放多个数据库连接对象.
2. JDBCTomcatPool,直接由 tomcat 产生数据库连接池.
3. 图示
3.1 active 状态:当前连接对象被应用程序使用中
3.2 Idle 空闲状态:等待应用程序使用
4. 使用数据库连接池的目的
4.1 在高频率访问数据库时,使用数据库连接池可以降低服务器系统压力,提升程序运行效率.
4.1.1 小型项目不适用数据库连接池.
5.实现 JDBCtomcatPool 的步骤.
5.1 在 web 项目的 META-INF 中存放 context.xml,在 context.xml 编写数据库连接池相关属性
<?xml version="1.0" encoding="UTF-8"?> <Context> <Resource driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/ssm" username="root" password="smallming" maxActive="50" maxIdle="20" name="test" auth="Container" maxWait="10000" type="javax.sql.DataSource" /> </Context>
5.2 把项目发布到 tomcat 中,数据库连接池产生了
6. 可以在 java 中使用 jndi 获取数据库连接池中对象
6.1Context:上下文接口.context.xml 文件对象类型
6.2 代码:
Context cxt = new InitialContext(); DataSource ds = (DataSource) cxt.lookup("java:comp/env/test"); Connection conn = ds.getConnection();//获取到数据库连接对象了,后面操作与JDBC相同
6.3 当关闭连接对象时,把连接对象归还给数据库连接池,把状态改变成 Idle