When access to a database is not frequent, you can establish a connection every time you access the database, and then close it when you are done. However, for a complex database application, frequent establishment, close connection, will greatly reduce the system performance, causing bottlenecks. So you can use the database connection pool to achieve the sharing of the connection resources, so that the connection to the database can be efficient and secure reuse.
1. Learn how database connection pooling works with a small test
(1) Create a property file Dbpool.properties
1 driverclassname=com.mysql.jdbc.driver
2 Username=root
3 password=iloveyou
4 url=jdbc:mysql://localhost:3306/student
5 poolsize=5
(2) Create a class file that implements the database connection pool Connectionpool.java
Connectionpool.java
(3) Create a class file that uses connection pooling to access the database Connectionpooltest.java
Connectionpooltest.java
2. There is no need to write a database connection pool yourself when developing a specific project, and now there are many ready-made components. Many servers have built-in database connection pools, such as Tomcat servers, JBoss servers, and WebLogic servers. I've configured the Tomcat server myself based on the example in the book. The configuration steps are as follows:
(1) Configure the files in \conf under the Tomcat root directory context.xml as follows:
1 <!--Resource Set the core of the database connection pool--
2 <!--Property The Name property of the name data source Auth represents the type of validation of the types resource--
3 <resource name= "Jdbc/dbwater" auth= "Container" type= "Javax.sql.DataSource"
4 maxactive= "maxidle=" "maxwait=" 10000 "
5 username= "root" password= "*******"
6 driverclassname= "Com.mysql.jdbc.Driver"
7 url= "Jdbc:mysql://localhost:3306/student"/>
Add this piece of code to <context></context>
(2) Modify the Webroot/web-inf/web.xml file under Project Engineering directory:
1 <resource-ref>
2 <!--description information--
3 <description>connection pool</description>
4 <!--data Source name matches the name of the data source in the configuration above--
5 <res-ref-name>jdbc/DBWater</res-ref-name>
6 <!--data Source Type-
7 <res-type>javax.sql.DataSource</res-type>
8 <res-auth>Container</res-auth>
9 <res-sharing-scope>Shareable</res-sharing-scope>
Ten </resource-ref>
You can use the connection pool below. For example, here, create a Dbwater.java file:
Dbwater.java
Then call the class in the JSP file:
1 <%@ page language= "java" import= "java.util.*" pageencoding= "gb2312"%>
2 <% @page import= "Com.lihui.dbwater.DBWater"%>
4 <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
5 6 7 <title> Connection pool testing </title>
8 9
Ten <body>
<%
Dbwater rs = new Dbwater ();
Rs.init ();
%>
Id:<%=rs.getuserid ()%>
Name:<%=rs.getname ()%>
Psd:<%=rs.getpassword ()%>
</body>
JDBC Database Connection Pooling Summary