One, the role of the connection pool
Database connection is a very important resource, if a project is smaller, the number of connections to the database is relatively small, we can take a direct connection: "Get connections----use----close connection." However, if a website is accessed very large, if there are millions of users at the same time, it will create millions of connections, so it is easy to crash the database, so that the site is paralyzed. At this time the database connection pool technology can play a role, the number of connections in the maintenance connection pool, if a request to connect, first look at the connection pool whether there is idle connection, if there is allocated out, run out, or the request must wait. This is a good solution to the pressure of the database. It's like going to a restaurant where we have to wait for the automatic arranging when there are too many people.
Second, the use of DBCP
1. Import the jar package.
DBCP relies on 3 jar packages.
Commons-dbcp2-2.1.1.jar
Commons-logging-1.1.1.jar
Commons-pool2-2.4.2.jar
In addition to connect the database also need a separate jar package, my database is MySQL, so I use: Mysql-connector-java-5.1.14.jar
2. Configuration parameters
Mode 1.: Configuration file configuration (dbcp.properties)
1 driverclassname=com.mysql.jdbc.Driver2 url=jdbc:mysql://localhost/ Paper_tag3 username=root4 password=admin5 maxactive=306 maxidle=107 maxwait=10008 initialsize=5
View Code
Method 2: Configure by code
Basicdatasource BDS = new Basicdatasource (); Bds.seturl (URL); Bds.setdriverclassname (driverclassname); Bds.setusername (username); Bds.setpassword (password); Bds.setinitialsize (initialsize); Bds.setmaxactive (maxactive); Bds.setminidle (minidle); Bds.setmaxidle (maxidle); Bds.setmaxwait (maxwait);
3. Get the connection
Here is the class that gets the connection Dbcputil
private static DataSource ds; private static final String configfile = "/dbcp.properties"; Public Dbcputil () {initdbcp (); } private void Initdbcp () {Properties prop = new Properties (); try {prop.load (Object.class.getResourceAsStream (configfile)); ds = Basicdatasourcefactory.createdatasource (prop); } catch (IOException e) {e.printstacktrace (); } catch (Exception e) {e.printstacktrace (); }} public Connection Getconn () {Connection conn = null; if (ds! = null) {try {conn = ds.getconnection (); Conn.setautocommit (FALSE); } catch (SQLException e) {e.printstacktrace (); }} return conn; } public static void Main (string[] args) {Dbcputil db = new Dbcputil (); System.out.println (Db.getconn ()); }}
DBCP of JDBC Database connection pool