Java uses DBCP2 database connection pool _java

Source: Internet
Author: User
Tags time limit

In development, we often use database connection pool, such as DBCP database connection pool, this chapter will explain the Java Connection DBCP Database Library connection pool simple use.
Development tools MYECLIPSE2014

1, first create a Web project, I named the project name Testjdbc, need to have a web.xml configuration file, the servlet configuration, the completion of the project after the creation of the following structure:

2, create the package, I created the package name is Com.szkingdom.db

3, create Help class Castutil, the code is as follows:

Package com.szkingdom.db; 
 /** * Created by Jack on 2015/12/26. 
   * Transformation Operation Tool class/public class Castutil {/* * to type String */public static string caststring (Object obj) { 
  return castutil.caststring (obj, ""); * * * To type String (provide default) */public static String caststring (Object obj, String defaultvalue) {return obj!= null? 
  String.valueof (obj): defaultvalue; 
  * * * to DOUBLE type * * */public static double castdouble (Object obj) {return castdouble (obj, double) 0); * * * to double type (provide default) */public static double castdouble (Object obj, double defaultvalue) {Doub 
   Le doublevalue = defaultvalue; 
    if (obj!= null) {String strvalue = caststring (obj); 
     if (Stringutil.isnotempty (strvalue)) {try {doublevalue = double.parsedouble (strvalue); 
     catch (NumberFormatException e) {defaultvalue = defaultvalue; 
  }} return doublevalue; } * * to LoNG Type * */public static long Castlong (Object obj) {return Castlong (obj, 0); * * * Switch to Long (provide default) */public static long Castlong (Object obj, long defaultvalue) {long Longvalu 
   e = defaultvalue; 
    if (obj!= null) {String strvalue = caststring (obj); 
     if (Stringutil.isnotempty (strvalue)) {try {longvalue = Long.parselong (strvalue); 
     }catch (NumberFormatException e) {longvalue=defaultvalue; 
  }} return longvalue; 
  * * * to INT type * * */public static int castint (Object obj) {return castint (obj,0); * * * to int type (provide default) */public static int castint (Object obj,int defaultvalue) {int Intvalue=defaultvalue 
   ; 
    if (obj!=null) {String strvalue=caststring (obj); 
     if (Stringutil.isnotempty (strvalue)) {try {intvalue=integer.parseint (strvalue); 
     }catch (NumberFormatException e) {intvalue=defaultvalue; }} return Intvalue; 
  * * * Convert to Boolean */public static Boolean Castboolean (Object obj) {return Castboolean (obj,false); * * * Convert to Boolean (provide default) */public static Boolean Castboolean (Object Obj,boolean defaultvalue) {Boolea 
   n Booleanvalue=defaultvalue; 
   if (obj!=null) {Booleanvalue=boolean.parseboolean (caststring (obj)); 
  return booleanvalue; 
 } 
}

4, create the property file read Help class Propsutil, the code is as follows:

Package com.szkingdom.db; 
Import java.io.FileNotFoundException; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import java.util.Properties; 
 /** * Created by Jack on 2015/12/26. * Property File Tool class */public class Propsutil {//private static final Logger Logger = Loggerfactory.getlogger (propsutil.class 
  
  ); 
   * * * Load Property File * */public static properties Loadprops (String fileName) {Properties properties = null; 
   InputStream inputstream = null; 
    try {InputStream = Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream (FileName); 
    if (InputStream = = null) {throw new FileNotFoundException (FileName + "file is not found!"); 
    Properties = new properties (); 
   Properties.load (InputStream); 
    catch (IOException e) {//logger.error ("Load Properties file Failure", e); 
   System.out.println ("Load Properties File failure:" +e); finally {if (InputStream!= null) {try {INPUTSTREAM.CLose (); 
      catch (IOException e) {//logger.error ("Close input stream failure", e); 
     SYSTEM.OUT.PRINTLN ("Close input stream failure:" +e); 
  }} return properties;  * * * Get character attribute (default is empty string) * */public static string getString (Properties props, String key) {return 
  GetString (props, Key, ""); * * * Get character attribute (default value can be specified) */public static String getString (properties props, String key, String defaul 
   TValue) {String value = defaultvalue; 
   if (Props.containskey (key)) {value = Props.getproperty (key); 
  return value; * * * Get numeric type properties (default 0) */public static int GetInt (properties props, String key) {return getInt props 
  , key, 0); 
   * * * Get numeric type properties (default value can be specified) */public static int GetInt (properties props, String key, int defaultvalue) { 
   int value = defaultvalue; 
   if (Props.containskey (key)) {value = Castutil.castint (Props.getproperty (key)); 
}   return value; /* * Get Boolean property (default is False) */public static Boolean Getboolean (Properties props, String key) {return 
  Getboolean (props, key, false); * * * Get Boolean attribute (default value can be specified) */public static Boolean Getboolean (properties props, String key, Boolean DEFAULTV 
   Alue) {Boolean value = DefaultValue; 
   if (Props.containskey (key)) {value = Castutil.castboolean (Props.getproperty (key)); 
  return value; 
 } 
}

5, create a String helper class Stringutil, the code is as follows:

Package com.szkingdom.db; 
/** 
 * Created by Jack on 2015/12/26. 
 * String Tool class 
 * 
/public class Stringutil 
 { 
  /* * To determine whether the string is null 
  * */Public 
  static Boolean IsEmpty (string STR) { 
   if (str!= null) { 
    Str=str.trim (); 
   } 
   return Stringutils.isempty (str); 
   Return "". Equals (str); 
  * 
  * To determine if the string is not NULL 
  * * 
  /public static Boolean Isnotempty (String str) {return 
   !isempty (str); 
  } 
 

6, in the SRC directory to create a database connection properties file Dbconfig.properties

<span style= "color: #333333;" >jdbc.driver=com.mysql.jdbc.driver 
jdbc.url=jdbc:mysql://</span><span style= "color: #ff6666; Background-color:rgb (255, 0, 0); >127.0.0.1:3306/****</span><span style= "color: #333333;" > 
jdbc.username=**** 
jdbc.password=****</span> 

7, put the necessary jar package into the Lib directory:

8, create a database Help class using DBCP

Package com.szkingdom.db; 
Import Java.io.ByteArrayInputStream; 
Import java.sql.Connection; 
Import Java.sql.DriverManager; 
Import java.sql.PreparedStatement; 
Import Java.sql.ResultSet; 
Import java.sql.SQLException; 
 
Import java.util.Properties; 
 
Import Org.apache.commons.dbcp2.BasicDataSource; /** * Created by Jack on 2015/12/26. Database Operations Assistant Class */public class Databasehelper {//private static final Logger logger=//Loggerfactory.getlogger (Databas 
 Ehelper.class); 
 private static final String DRIVER; 
 private static final String URL; 
 private static final String USERNAME; 
 private static final String PASSWORD; 
 Ensure a thread-Connection, thread-safe private static final threadlocal<connection> Connection_holder; 
 Thread pool private static final Basicdatasource data_source; 
   
  static {Connection_holder = new threadlocal<connection> (); 
  Properties conf = propsutil.loadprops ("dbconfig.properties"); 
  DRIVER = Conf.getproperty ("Jdbc.driver"); URL = CONF.GEtproperty ("Jdbc.url"); 
  USERNAME = Conf.getproperty ("Jdbc.username"); 
   
  PASSWORD = Conf.getproperty ("Jdbc.password"); 
  String Driver = Conf.getproperty ("Jdbc.driver"); 
  String url = conf.getproperty ("Jdbc.url"); 
  String username = conf.getproperty ("Jdbc.username"); 
   
  String Passwrod = Conf.getproperty ("Jdbc.password"); 
  Data_source=new Basicdatasource (); 
  Data_source.setdriverclassname (driver); 
  Data_source.seturl (URL); 
  Data_source.setusername (username); 
  Data_source.setpassword (Passwrod); Database connection Pool parameter configuration: http://www.cnblogs.com/xdp-gacl/p/4002804.html//http://greemranqq.iteye.com/blog/1969273//http:// blog.csdn.net/j903829182/article/details/50190337//http://blog.csdn.net/jiutianhe/article/details/39670817// http://bsr1983.iteye.com/blog/2092467//http://blog.csdn.net/kerafan/article/details/50382998//http:// 
  blog.csdn.net/a9529lty/article/details/43021801///Sets the maximum total number of idle and borrowed connections, which can be activated at the same time. 
  Data_source.setmaxtotal (60); Set Initial Size DATA_source.setinitialsize (10); 
  Minimum idle connection data_source.setminidle (8); 
  Maximum Idle connection data_source.setmaxidle (16); 
  Timeout wait time millisecond data_source.setmaxwaitmillis (2*10000); 
  Only the current connection is found to be invalid, and then a connection is created for the current query to use Data_source.settestonborrow (true); 
  Removeabandonedtimeout: More than time limit, recycling is not used (obsolete) connection (default is 300 seconds, adjusted to 180) data_source.setremoveabandonedtimeout (180); removeabandoned: No unused connection (OBSOLETE) recycle (default is False, adjusted to true) after removeabandonedtimeout time is exceeded//data_ 
  Source.setremoveabandonedonmaintenance (removeabandonedonmaintenance); 
  Data_source.setremoveabandonedonborrow (TRUE); 
  Testwhileidle Data_source.settestonreturn (TRUE); 
  Testonreturn Data_source.settestonreturn (TRUE); 
  Setremoveabandonedonmaintenance data_source.setremoveabandonedonmaintenance (TRUE); 
   
  Log data_source.setlogabandoned (TRUE); 
  Set autocommit Data_source.setdefaultautocommit (true); 
  Data_source.setenableautocommitonreturn (TRUE); System.out.println ("complete Setting the parameters of the database connection pool Data_source!!") 
  "); /*try {ClAss.forname (DRIVER); 
  SYSTEM.OUT.PRINTLN ("Load JDBC driver success"); 
   catch (ClassNotFoundException e) {//Logger.error ("Can not load JDBC driver", e); 
  System.out.println ("Can not load JDBC driver:" + e); }finally{}*/}//private static final threadlocal<connection> Connection_holder = new Threadlocal<co 
 
 Nnection> (); /** * Get database connection/public static Connection getconnection () {Connection conn = Connection_holder.get ();//1 I 
    F (conn = = null) {try {//conn = drivermanager.getconnection (URL, USERNAME, PASSWORD); 
    conn = Data_source.getconnection (); 
   SYSTEM.OUT.PRINTLN ("Get connection Success"); 
    catch (SQLException e) {//Logger.error ("Get connection Failure", e); 
   SYSTEM.OUT.PRINTLN ("Get connection failure:" + e); 
    finally {/*system.out.println ("Minimum idle Connection minidle=" +data_source.getminidle ()); 
    SYSTEM.OUT.PRINTLN ("Maximum idle connection maxidle=" +data_source.getmaxidle ()); System.out.println ("Max CompanyNumber of maxtotal= "+data_source.getmaxtotal ()); 
    SYSTEM.OUT.PRINTLN ("Initial Size initialsize=" +data_source.getinitialsize ()); 
    SYSTEM.OUT.PRINTLN ("Timeout wait time maxwaitmillis=" + (Data_source.getmaxwaitmillis ()/1000)); 
    SYSTEM.OUT.PRINTLN ("Get Active Connection number getnumactive () =" +data_source.getnumactive ()); 
   System.out.println ("Get Connected number getnumidle=" +data_source.getnumidle ()); * * CONNECTION_HOLDER.SET (conn); 
 } return conn; 
  /** * Close database connection/public static void CloseConnection () {Connection conn = Connection_holder.get ();//1 
    IF (conn!= null) {try {conn.close (); 
   SYSTEM.OUT.PRINTLN ("Close connection success"); 
    catch (SQLException e) {//Logger.error ("Close connection failure", e); 
    SYSTEM.OUT.PRINTLN ("Close connection failure:" + e); 
   throw new RuntimeException (e); 
   finally {connection_holder.remove (); Database operations public static synchronized void update (int thlsh,string ltnr) {Connection conn = GetConnect IOn (); 
  if (conn==null) {System.out.println ("the () connection in the Update method is null!!"); 
  } PreparedStatement Pstmt=null; 
  System.out.println ("Update begins!"); 
  int ltlsh=0; 
   try {//string sql= "update message set CONTENT = where id=?"; 
   String sql1= "Select Ltlsh from T_zxthlsk where lsh =?"; String sql= "Update t_wx_ltnrk b set B.ltnr =? 
    
   where B.lsh = "+" (select A.ltlsh from T_zxthlsk a where a.lsh =?) "; 
   SYSTEM.OUT.PRINTLN ("Updated SQL statement is:sql->" +sql); 
   pstmt = conn.preparestatement (sql); 
   Pstmt.setblob (1, New Bytearrayinputstream (Ltnr.getbytes ())); 
   Pstmt.setint (2, Thlsh); 
   /*pstmt.setstring (1, "This is DBCP2 Test 2222"); 
    Pstmt.setint (2, 6); */if (pstmt.executeupdate () >0) {//system.out.println ("Update id=1 data Successful!"); 
   System.out.println ("Update thlsh=" +thlsh+ Chat content data successfully!\n chat content is: "+LTNR); 
    
   }//conn.commit (); 
    /*while (Rs1.next ()) {Ltlsh = Rs1.getint ("Ltlsh"); SYSTEM.OUT.PRINTLN ("Query chat serial number success, chat serial number for ltlsh->" +ltlsh); 
   }*///pstmt.setstring (1, "Wonderful content update1"); 
   Pstmt.setint (2, 1); 
   Pstmt.setblob (1, New Bytearrayinputstream ("12345 China". GetBytes ())); 
   Pstmt.setint (2, 76732); 
    /*if (Pstmt.executeupdate () >0) {//system.out.println ("Update id=1 data Successful!"); 
   System.out.println ("Update id=76732 data Success!"); 
  Conn.commit (); * * SYSTEM.OUT.PRINTLN ("Update t_wx_ltnrk success"); 
   catch (SQLException e) {//logger.error ("Query entity list failure", e); 
   SYSTEM.OUT.PRINTLN ("Update data exception connection=" +conn); 
   System.out.println ("Update T_WX_LTNRK failure:" + e); 
  throw new RuntimeException (e); 
   finally {//closeconnection (); 
   CloseConnection (); 
    if (pstmt!=null) {try {pstmt.close (); 
     catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); 
    System.out.println ("PreparedStatement failure"); 
    } if (Conn!=null) {try {conn.close (); catch (SQLException e) {//TOdo auto-generated catch block E.printstacktrace (); 
   }//Remove the CONNECTION in the thread, not remove will cause CONNECTION shutdown, the obtained CONNECTION is off state, can not perform data operation Connection_holder.remove (); 
  CloseConnection (); 
 }//return entitylist; 
 } 
  
  
}

9, the basic database connection pool was created, then you can use the Databasehelper Update method to simulate the acquisition of database connection database operation, according to their own needs for the operation of data.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.