1 Packagecn.itsource._03_dbcp;2 3 ImportJava.io.InputStream;4 Importjava.sql.Connection;5 ImportJava.sql.ResultSet;6 Importjava.sql.SQLException;7 Importjava.sql.Statement;8 Importjava.util.Properties;9 Ten ImportJavax.sql.DataSource; One A Importorg.apache.commons.dbcp.BasicDataSourceFactory; - - Public classDbcputil { the Private StaticDataSource DataSource; - //use static blocks of code so that the driver is loaded when the tool class is invoked and loaded only once - Static { - Try { + //First, create the properties object that is used to load the properties configuration file -Properties prop =NewProperties (); + //get DBCP Profile input stream AInputStream instream =Thread.CurrentThread (). Getcontextclassloader () at. getResourceAsStream ("Dbcp.properties"); - /* - * Note: The key in the configuration file must meet the Basicdatasource - The setter property in, that is, the value of key is the second half of several methods, such as setting the Connection property "Setdriverclassname (str)" In Basicdatasource, - that is, Driverclassname,username,url,password and initialsize (number of initial connections created when connection pooling starts) "*/ - in //Load configuration file - prop.load (instream); to /* + using the Basicdatasourcefactory static method Createsource (prop), - creates a DataSource connection pool object from a prop object that already has the properties file loaded;*/ theDataSource =Basicdatasourcefactory.createdatasource (prop); *}Catch(Exception e) { $ e.printstacktrace ();Panax Notoginseng } - } the + //methods to return connection objects A Public StaticConnection Getconnec () { the //creating connection objects using DataSource's Getconnection method + Try { - returndatasource.getconnection (); $}Catch(SQLException e) { $ e.printstacktrace (); - } - return NULL; the } - Wuyi //methods for closing resources and their exception handling the Public Static voidClose (ResultSet rSet, Statement State, Connection Connec) { - Try { Wu if(RSet! =NULL) - rset.close (); About}Catch(SQLException e) { $ e.printstacktrace (); -}finally { - - Try { A if(state! =NULL) + state.close (); the}Catch(SQLException e) { - e.printstacktrace (); $}finally { the the Try { the if(Connec! =NULL) the connec.close (); -}Catch(SQLException e) { in e.printstacktrace (); the } the } About } the } the}
// This is the content of the properties file driverclassname=com.mysql.jdbc.Driverurl=jdbc:mysql://Localhost:3306/jdbcdemo username=rootpassword=4230initialsize=5
dbcp--"Connection pool creation" and "Resource Close" Util class