First step: Import the DBCP package
Step two: Connect data through the core class
Basicdatasource It is a subclass of Javax.sql.DataSrouce.
A tool class: Basicdatasourcefactory.
Manually connect to the database by code:
Basicdatasource ds =NewBasicdatasource (); //Set DriverDs.setdriverclassname ("Com.mysql.jdbc.Driver"); //Set URLDs.seturl ("Jdbc:mysql:///db909?characterencoding=utf8"); Ds.setpassword ("1234"); Ds.setusername ("Root"); Ds.setmaxactive (5) ;//set up a few connectionsDs.setinitialsize (2);//set to create several connections at the beginning
Manual connection, do not recommend this.
Step three: Create a resource file
In DBCP, a class is specifically used to read resource files:
Basicdatasourcefactory
#以下所有属性, all from Baiscdatasource's setxxxx.
Add a configuration file jdbc.propertiesdriverclassname=Com.mysql.jdbc.Driverurl=jdbc:mysql:///db909Username=Rootpassword=1234maxactive=3Properties P=NewProperties (); P.load (Dbcppool.class. getResourceAsStream ("jdbc.properties")); DataSource DS=NewBasicdatasourcefactory (). CreateDataSource (P);
Fourth step, using connection pooling
In a project, you can only have one instance of datasource. There are several connectioin in this dataqSource3.
Declare a factory class, create a DataSource that maintains only one
Package Cn.itcast.utils;import java.sql.connection;import java.sql.sqlexception;import java.util.Properties; Import Javax.sql.datasource;import org.apache.commons.dbcp.BasicDataSourceFactory; Public classDatasourceutils {Privatedatasourceutils () {}Private StaticDataSource ds; Static{ Try{Properties P=NewProperties (); P.load (datasourceutils.class. getClassLoader (). getResourceAsStream ("jdbc.properties")); DS=Newbasicdatasourcefactory (). CreateDataSource (P); }Catch(Exception e) {}}//returns a unique connection Public StaticConnection Getcon () {Connection con=NULL; Try{con=ds.getconnection (); } Catch(SQLException e) {e.printstacktrace (); } returncon; } //provides a way to return datasource Public StaticDataSource Getds () {returnds; }}
Java Learning notes-third-party database connection Pool Pack 1 (29)