Java learning notes-third-party database connection pool Package 1 (29), java learning notes
Step 1: import the dbcp package
BasicDataSource ds = new BasicDataSource (); // you can specify the driver ds. setDriverClassName ("com. mysql. jdbc. driver "); // set the url ds. setUrl ("jdbc: mysql: // db909? CharacterEncoding = UTf8 "); ds. setPassword ("1234"); ds. setUsername ("root"); ds. setMaxActive (5); // you can set up to several connections to ds. setInitialSize (2); // sets the number of connections created at the start.
Manual connection is not recommended.
Step 3: create a resource file
In dbcp, a class is specifically used to read resource files:
BasicDataSourceFactory
# All the following attributes are from the setXxxx of BaiscDataSource
// Add a configuration file jdbc. propertiesdriverClassName = com. mysql. jdbc. driverurl = jdbc: mysql: // db909username = rootpassword = 1234 maxActive = 3 Properties p = new Properties (); p. load (DbcpPool. class. getResourceAsStream ("jdbc. properties "); DataSource ds = new BasicDataSourceFactory (). createDataSource (p );
Step 4: Use the connection pool
In a project, you can only have one DataSource instance. There are multiple Connectioin in this dataqsours3.
Declare a factory class and create a unique DataSource for maintenance
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 class DataSourceUtils {private DataSourceUtils () {} private static DataSource ds; static {try {Properties p = new Properties (); p. load (performanceutils. class. getClassLoader (). getResourceAsStream ("jdbc. properties "); ds = new BasicDataSourceFactory (). createDataSource (p);} catch (Exception e) {}} // returns a unique Connection public static Connection getCon () {Connection con = null; try {con = ds. getConnection ();} catch (SQLException e) {e. printStackTrace ();} return con;} // provides a method to return DataSource public static DataSource getDs () {return ds ;}}