Welcome to the Csdn-markdown Editor

Source: Internet
Author: User
Tags log log

Using DBCP in Java EE

Access to database data is essential when using Java for Web site development, and DBCP has a unique advantage in managing database connections.

Dbcp

DBCP (database connection pool), DB connection pool. is a Java Connection pool project on Apache and a connection pool component used by Tomcat. Use of DBCP alone requires 2 packages: Commons-dbcp.jar, Commons-pool.jar because establishing a database connection is a very time-consuming and resource-intensive behavior, the connection pool is pre-established with the database to make some connections, put in memory, the application needs to establish a database connection directly to the connection pool to apply for a line, run out and then put back. --[Baidu Encyclopedia]

Simply said is an Apache has been compiled database connection pool, directly to use can. It is faster and more efficient than the program you write to access the data.

How to use
    • Environment description
      Please note: I use MySQL database

    • Preparatory work

      1. Mysql-connector-java-5.1.26-bin.jar, this is the JDBC driver for MySQL, downloaded and placed under the Webcontent/web-inf/lib file

      2. Commons-dbcp-1.4.jar,commons-pool-1.5.6.jar, these two jars are two jar packages necessary for DBCP to be downloaded and introduced into the project (i.e., introduced into the project in the form of built path)

      3. Commons-logging-1.1.3.jar, this one log jar package, I want to say is, if is the development project, try to keep the habit of using the log, do a good job in the project development, project maintenance has a great help. Also introduced into the project in the form of built path

code block

If the prep work is done, the code starts here.

Dbmanager class

ImportJava.sql.Connection;ImportJava.sql.DatabaseMetaData;ImportJava.sql.SQLException;ImportJava.util.Properties;ImportJavax.sql.DataSource;ImportOrg.apache.commons.dbcp.BasicDataSourceFactory;ImportOrg.apache.commons.logging.Log;ImportOrg.apache.commons.logging.LogFactory; Public  class DBManager {    Private Static FinalLog log = Logfactory.getlog (Dbmanager.class);Private Static FinalString ConfigFile ="Dbcp.properties";Private StaticDataSource DataSource;Static{Properties dbproperties =NewProperties ();Try{Dbproperties.load (DBManager.class.getClassLoader (). getResourceAsStream (ConfigFile));            DataSource = Basicdatasourcefactory.createdatasource (dbproperties);            Connection conn = Getconn ();            DatabaseMetaData mdm = Conn.getmetadata (); Log.info ("Connected to"+ mdm.getdatabaseproductname () +" "+ mdm.getdatabaseproductversion ());if(Conn! =NULL) {conn.close (); }        }Catch(Exception e) {Log.error ("Initialization of Connection pool failed:"+ e);        E.printstacktrace (); }    }Private DBManager(){} Public Static FinalConnectionGetconn() {Connection conn =NULL;Try{conn = datasource.getconnection (); }Catch(SQLException e) {Log.error ("Get database Connection failed:"+ e); }returnConn } Public Static void Closeconn(Connection conn) {Try{if(Conn! =NULL&&!conn.isclosed ()) {Conn.setautocommit (true);            Conn.close (); }        }Catch(SQLException e) {Log.error ("failed to close database connection:"+ e); }    }}

Among them, ConfigFile = "dbcp.properties" actually refers to a configuration file, the specific content is as follows:

Dbcp.properties

driverClassName=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/数据库名username=root        password=1234556maxActive=30maxIdle=10maxWait=1000removeAbandoned=trueremoveAbandonedTimeout=180

The meaning of each parameter, please search by yourself, do not repeat here.
Note: The dbcp.properties file is placed under the src file

Test class Tomcatdbtest Class

 PackageDbbase;ImportJava.sql.Connection;ImportJava.sql.SQLException; Public  class tomcatdbtest {     Public Static void Main(string[] args) {Connection conn = Dbmanager.getconn ();if(Conn! =NULL) {System.out.println ("Successfully established connection");Try{Conn.close (); }Catch(SQLException e) {System.out.println ("Connection not successfully closed");            E.printstacktrace (); }return; } System.out.println ("Failed to connect to the database!" "); }}
Conclusion

The above description and code refer to the following Web site, to pay tribute to the provider.
[Reference website for code and description]

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Welcome to the Csdn-markdown Editor

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.