1. Because the database can be accessed by an instance in general cases, you can design the class into a singleton mode. For example:
Public class dbutil {
// The design constructor is private and cannot be created or inherited by other classes.
Private dbutil (){}
Private Static dbutil instance = NULL;
// Provides an external Creation Method
Public synchronized static dbutil getdbutilinstance (){
If (instance = NULL ){
Instance = new dbutil ();
}
Return instance;
}
}
2. Load the database driver and enter the name of the database driver.
Class. forname (""); or drivermanager. registerdriver (name of a new driver );
3. Obtain the connection object
Drivermanager. getconnection (URL, username, password );
Database Connection Pool: There are two main types: DBCP and c3p0.
DBCP: You need to import two jar packages, commons-dbcp-1.2.2.jar and commons-pool.jar
1. Two member variables basicdatasource and cececonnectionfactory are required.
2. Create a basicdatasource object and call seturl () setdriverclassname () setusername () setpassword () to set JDBC-related information.
3. you can choose to set the connection pool configuration, call the setinitialsize (20) function --- set the initial connection count setmaxactive (100) --- the maximum number of retrieved connections setminidle (10) --- the minimum number of available idle connections setmaxidle () --- maximum number of available idle connections
4. Create the cececonnectionfactory object and pass in the basicdatasource object as the parameter
5. Call the createconnection method through the datasourceconnectionfactory object to return the connection
C3p0: need to import c3p0-0.9.1.jar package
1. A Member variable combopooleddatasource is required.
2. Create a combopooleddatasource object and call setjdbcurl () setuser () setpassword () to set JDBC-related information.
3. Set the connection pool and call setinitialpoolsize (30) setmaxpoolsize (100) setminpoolsize (10)
4. Call the getconnection method to return the connection object
* ** DBCP is efficient, but c3p0 is stable. Therefore, c3p0 is widely used.