[JavaEE] open source database connection pool and javaee database connection
Some open-source organizations provide independent implementation of data sources:
DBCP database connection pool
C3P0 database connection pool
Built-in connection pool of Apache Tomcat
DBCP connection pool
The connection pool implementation provided by apache needs to import common-dbcp.jar commons-pool.jar
Import java. io. fileReader; import java. SQL. connection; import java. SQL. resultSet; import java. SQL. statement; import java. util. properties; import javax. SQL. dataSource; import org. apache. commons. dbcp. basicDataSourceFactory; public class DBCPTest {public static void main (String [] args) throws Exception {// import the configuration file Properties prop = new Properties (); prop. load (new FileReader ("dbcp. properties "); // obtain the data source BasicDataSourceFactory = new BasicDataSourceFactory (); DataSource pool = factory. createDataSource (prop); Connection conn = pool. getConnection (); // get the transmitter object Statement statement = conn. createStatement (); // obtain the result set object ResultSet resultSet=statement.exe cuteQuery ("select * from user"); // traverse while (resultSet. next () {String username = resultSet. getString ("username"); System. out. println (username);} // closes the resource resultSet. close (); statement. close (); conn. close ();}}
Create dacp. properties in the project directory
driverClassName=com.mysql.jdbc.Driverurl=jdbc:mysql:///javausername=rootpassword=root
C3P0 connection pool
Import java. SQL. connection; import java. SQL. resultSet; import java. SQL. statement; import com. mchange. v2.c3p0. comboPooledDataSource; public class DBCPTest {public static void main (String [] args) throws Exception {// use C3P0 ComboPooledDataSource pool = new ComboPooledDataSource (); Connection conn = pool. getConnection (); // get the transmitter object Statement statement = conn. createStatement (); // obtain the result set object ResultSet resultSet=statement.exe cuteQuery ("select * from user"); // traverse while (resultSet. next () {String username = resultSet. getString ("username"); System. out. println (username);} // closes the resource resultSet. close (); statement. close (); conn. close ();}}
C3P0 needs to create a new c3p0-config.xml under the class load directory
<?xml version="1.0" encoding="utf-8"?><c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///java</property> <property name="user">root</property> <property name="password">root</property> </default-config></c3p0-config>