DBCP data source usage, dbcp Data Source

Source: Internet
Author: User

DBCP data source usage, dbcp Data Source
DBCP: DataBase Connection Pool
1, the need for jar: commons-dbcp.jar commons-pool.jar

2. Copy the DBCP configuration file (dbcpconfig. properties) to the build path.

3. Create a class: DBCPUtil

Dbcpconfig. properties:

The mysql settings are as follows:

# Connection setting driverClassName = com. mysql. jdbc. Driverurl = jdbc: mysql: // localhost: 3306/day16username = rootpassword = liang # <! -- Initialize connection --> initialSize = 10 # maximum number of connections maxActive = 50 # <! -- Maximum idle connection --> maxIdle = 20 # <! -- Minimum idle connection --> minIdle = 5 # <! -- The timeout wait time is in milliseconds. The unit is 6000 milliseconds/1000 is equal to 60 seconds. --> maxWait = 60000 # The format of the connection attribute that is attached to the JDBC driver when establishing a connection must be as follows: [property name = property;] # Note: the "user" and "password" attributes are passed explicitly, so they are not included here. ConnectionProperties = useUnicode = true; characterEncoding = utf8 # specify the auto-commit status of the connection created by the connection pool. DefaultAutoCommit = true # driver default specifies the read-only status of the connection created by the connection pool. # If this value is not set, the "setReadOnly" method will not be called. (Some drivers do not support read-only mode, such as Informix.) defaultReadOnly = # driver default specifies the transaction level (TransactionIsolation) of the connection pool ). # The available value is one of the following: (for details, see javadoc .) NONE, READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE # oracle only supports READ_COMMITTED (default), SERIALIZABLEdefaultTransactionIsolation = REPEATABLE_READ


DBCPUtil:

package cn.itcast.util;import java.io.InputStream;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;import javax.sql.DataSource;import org.apache.commons.dbcp.BasicDataSourceFactory;public class DBCPUtil {private static DataSource ds;static{try {InputStream in = DBCPUtil.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");Properties props = new Properties();props.load(in);ds = BasicDataSourceFactory.createDataSource(props);} catch (Exception e) {e.printStackTrace();}}public static Connection getConnection(){try {return ds.getConnection();} catch (SQLException e) {throw new RuntimeException(e);}}public static void release(ResultSet rs,Statement stmt,Connection conn){if(rs!=null){try {rs.close();} catch (SQLException e) {e.printStackTrace();}rs = null;}if(stmt!=null){try {stmt.close();} catch (SQLException e) {e.printStackTrace();}stmt = null;}if(conn!=null){try {conn.close();} catch (SQLException e) {e.printStackTrace();}conn = null;}}}





How to Use dbcp

A connection pool. This is simple.
Import java. SQL. connection; import java. SQL. resultSet; import java. SQL. SQLException; import java. SQL. statement; import java. util. hashMap; import java. util. map; import javax. SQL. dataSource; import org. apache. commons. dbcp. basicDataSource;/*** @ date Aug 12,200 8 3:25:49 PM ** dbcp connector class, which provides a dbcp connection and does not allow inheritance. ** this class must have a place to initialize DS, you can call the initDS method by calling the constructor with parameters. */public final class DbcpBean {/** data source */private Da TaSource Ds;/** get a Connection from the data source */public Connection getConn () {Connection con = null; if (Ds! = Null) {try {con = Ds. getConnection ();} catch (Exception e) {e. printStackTrace (System. err);} try {con. setAutoCommit (false);} catch (SQLException e) {e. printStackTrace ();} return con;}/** default constructor */public DbcpBean () {}/ **, initialized DS, specify database */public DbcpBean (String connectURI) {initDS (connectURI);}/** constructor, initialize DS, specify all parameters */public DbcpBean (String connectURI, string username, String pswd, String driverClass, int initialSize, int maxActive, int maxIdle, int maxWait) {initDS (connectURI, username, pswd, driverClass, initialSize, maxActive, maxIdle, maxWait);}/*** create a data source. hard-coded default parameters are used in addition to databases; ** @ param connectURI database * @ return */public void initDS (Str ...... remaining full text>

How to Use dbcp in jdbc

There are not many cases of direct use.

It is usually used with the framework, so the configuration is complete.

Direct use

Public final class JdbcUtils {

Private static DataSource myDataSource = null;

Private JdbcUtils (){
}

Static {
Try {
Class. forName ("com. mysql. jdbc. Driver ");
// MyDataSource = new myperformance2 ();
Properties prop = new Properties ();
// Prop. setProperty ("driverClassName", "com. mysql. jdbc. Driver ");
// Prop. setProperty ("user", "user ");
InputStream is = JdbcUtils. class. getClassLoader (). getResourceAsStream ("dbcpconfig. properties ");
Prop. load (is );
MyDataSource = BasicDataSourceFactory. createDataSource (prop); // create a data source. The code is complete.
} Catch (Exception e ){
Throw new ExceptionInInitializerError (e );
}
}

Public static DataSource getDataSource (){
Return myDataSource;
}

Public static Connection getConnection () throws SQLException {
// Return DriverManager. getConnection (url, user, password );
Return myDataSource. getConnection ();
}

Public static void free (ResultSet rs, Statement st, Connection conn ){
Try {
If (rs! = Null)
Rs. close ();
} Catch (SQLException e ){
E. printStackTrace ();
} Finally {
Try {
If (st! = Null)
St. close ();
} Catch (SQLExcept ...... remaining full text>
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.