当前位置: 移动技术网 > IT编程>开发语言>Java > java使用dbcp2数据库连接池

java使用dbcp2数据库连接池

2019年07月22日  | 移动技术网IT编程  | 我要评论

在开发中中我们经常会使用到数据库连接池,比如dbcp数据库连接池,本章将讲解java连接dbcp数据库库连接池的简单使用。
开发工具myeclipse2014

1、首先创建一个web项目,我把项目名取名为testjdbc,需要带有web.xml的配置文件,进行servlet的配置,创建完成以后的项目结构如下:

2、创建包,我创建的包名是com.szkingdom.db

3、创建帮助类castutil,代码如下:

package com.szkingdom.db; 
/** 
 * created by jack on 2015/12/26. 
 * 转型操作工具类 
 */ 
public class castutil { 
  /* 
  * 转为string型 
  * */ 
  public static string caststring(object obj) { 
   return castutil.caststring(obj, ""); 
  } 
  
  /* 
  * 转为string型(提供默认值) 
  * */ 
  public static string caststring(object obj, string defaultvalue) { 
   return obj != null ? string.valueof(obj) : defaultvalue; 
  } 
  
  /* 
  * 转为double型 
  * */ 
  public static double castdouble(object obj) { 
   return castdouble(obj, (double)0); 
  } 
  
  /* 
  * 转为double型(提供默认值) 
  * */ 
  public static double castdouble(object obj, double defaultvalue) { 
   double 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; 
  } 
  
  /* 
  * 转为long型 
  * */ 
  public static long castlong(object obj) { 
   return castlong(obj, 0); 
  } 
  
  /* 
   * 转为long型(提供默认值) 
   * */ 
  public static long castlong(object obj, long defaultvalue) { 
   long longvalue = defaultvalue; 
   if (obj != null) { 
    string strvalue = caststring(obj); 
    if (stringutil.isnotempty(strvalue)) { 
     try { 
      longvalue = long.parselong(strvalue); 
     }catch (numberformatexception e){ 
      longvalue=defaultvalue; 
     } 
  
    } 
   } 
   return longvalue; 
  } 
  
  /* 
  * 转为int型 
  * */ 
  public static int castint(object obj){ 
   return castint(obj,0); 
  } 
  /* 
  * 转为int型(提供默值) 
  * */ 
  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; 
  } 
  
  /* 
  * 转为boolean型 
  * */ 
  public static boolean castboolean(object obj){ 
   return castboolean(obj,false); 
  } 
  /* 
  * 转为boolean型(提供默认值) 
  * */ 
  public static boolean castboolean(object obj,boolean defaultvalue){ 
   boolean booleanvalue=defaultvalue; 
   if(obj!=null){ 
    booleanvalue=boolean.parseboolean(caststring(obj)); 
   } 
   return booleanvalue; 
  } 
} 

4、创建属性文件读取帮助类propsutil,代码如下:

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. 
 * 属性文件工具类 
 */ 
public class propsutil { 
  //private static final logger logger = loggerfactory.getlogger(propsutil.class); 
  
  /* 
  * 加载属性文件 
  * 
  * */ 
  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; 
  } 
  
  /* 
  * 获取字符型属性(默认为空字符串) 
  * 
  * */ 
  public static string getstring(properties props, string key) { 
   return getstring(props, key, ""); 
  } 
  
  /* 
  * 获取字符型属性(可指定默认值) 
  * */ 
  public static string getstring(properties props, string key, string 
    defaultvalue) { 
   string value = defaultvalue; 
   if (props.containskey(key)) { 
    value = props.getproperty(key); 
   } 
   return value; 
  } 
  
  /* 
  * 获取数值类型属性(默认为0) 
  * */ 
  public static int getint(properties props, string key) { 
   return getint(props, key, 0); 
  } 
  
  /* 
  * 获取数值类型属性(可指定默认值) 
  * */ 
  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; 
  } 
  
  /* 
  * 获取布尔型属性(默认值为false) 
  * */ 
  public static boolean getboolean(properties props, string key) { 
   return getboolean(props, key, false); 
  } 
  
  /* 
  * 获取布尔型属性(可指定默认值) 
  * */ 
  public static boolean getboolean(properties props, string key, boolean defaultvalue) { 
   boolean value = defaultvalue; 
   if (props.containskey(key)) { 
    value = castutil.castboolean(props.getproperty(key)); 
   } 
   return value; 
  } 
} 

5、创建一个字符串帮助类stringutil,代码如下:

package com.szkingdom.db; 
/** 
 * created by jack on 2015/12/26. 
 * 字符串工具类 
 */ 
public class stringutil { 
 /* 
  * 判断字符串是否为空 
  * */ 
  public static boolean isempty(string str){ 
   if(str != null){ 
    str=str.trim(); 
   } 
   //return stringutils.isempty(str); 
   return "".equals(str); 
  } 
  /* 
  * 判断字符串是否非空 
  * */ 
  public static boolean isnotempty(string str){ 
   return !isempty(str); 
  } 
} 

6、在src目录下创建一个数据库连接的属性文件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、把必备的jar包放到lib目录下:

8、使用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. 数据库操作助手类 
 */ 
public class databasehelper { 
 // private static final logger logger= 
 // loggerfactory.getlogger(databasehelper.class); 
 private static final string driver; 
 private static final string url; 
 private static final string username; 
 private static final string password; 
 //保证一个线程一个connection,线程安全 
 private static final threadlocal<connection> connection_holder ; 
 //线程池 
 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); 
  //数据库连接池参数配置: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 
  ///设置空闲和借用的连接的最大总数量,同时可以激活。 
  data_source.setmaxtotal(60); 
  //设置初始大小 
  data_source.setinitialsize(10); 
  //最小空闲连接 
  data_source.setminidle(8); 
  //最大空闲连接 
  data_source.setmaxidle(16); 
  //超时等待时间毫秒 
  data_source.setmaxwaitmillis(2*10000); 
  //只会发现当前连接失效,再创建一个连接供当前查询使用 
  data_source.settestonborrow(true); 
  //removeabandonedtimeout :超过时间限制,回收没有用(废弃)的连接(默认为 300秒,调整为180) 
  data_source.setremoveabandonedtimeout(180); 
  //removeabandoned :超过removeabandonedtimeout时间后,是否进 行没用连接(废弃)的回收(默认为false,调整为true) 
  //data_source.setremoveabandonedonmaintenance(removeabandonedonmaintenance); 
  data_source.setremoveabandonedonborrow(true); 
  //testwhileidle 
  data_source.settestonreturn(true); 
  //testonreturn 
  data_source.settestonreturn(true); 
  //setremoveabandonedonmaintenance 
  data_source.setremoveabandonedonmaintenance(true); 
  //记录日志 
  data_source.setlogabandoned(true); 
   
  //设置自动提交 
  data_source.setdefaultautocommit(true); 
  // data_source.setenableautocommitonreturn(true); 
  system.out.println("完成设置数据库连接池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<connection>(); 
 
 /** 
  * 获取数据库连接 
  */ 
 public static connection getconnection() { 
  connection conn = connection_holder.get();// 1 
  if (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(" 最小空闲连接minidle="+data_source.getminidle()); 
    system.out.println(" 最大空闲连接maxidle="+data_source.getmaxidle()); 
    system.out.println(" 最大连接数量maxtotal="+data_source.getmaxtotal()); 
    system.out.println(" 初始大小initialsize="+data_source.getinitialsize()); 
    system.out.println(" 超时等待时间maxwaitmillis="+(data_source.getmaxwaitmillis()/1000)); 
    system.out.println(" 获取活动的连接数getnumactive()="+data_source.getnumactive()); 
    system.out.println(" 获取连接数getnumidle="+data_source.getnumidle());*/ 
    connection_holder.set(conn); 
   } 
  } 
  return conn; 
 } 
 
 /** 
  * 关闭数据库连接 
  */ 
 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(); 
   } 
  } 
 } 
 
 //进行数据库操作 
 public static synchronized void update(int thlsh,string ltnr) { 
  connection conn = getconnection(); 
  if(conn==null){ 
   system.out.println("update方法里面的()connection为null!!"); 
  } 
  preparedstatement pstmt=null; 
  system.out.println("update开始!"); 
  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("更新的sql语句为: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("更新id=1的数据成功!"); 
    system.out.println("更新thlsh="+thlsh+"的聊天内容数据成功!\n聊天内容为:"+ltnr); 
   } 
   //conn.commit(); 
    
   /*while(rs1.next()){ 
    ltlsh = rs1.getint("ltlsh"); 
    system.out.println("查询聊天流水号成功,聊天流水号为ltlsh->"+ltlsh); 
   }*/ 
    
   //pstmt.setstring(1, "精彩内容update1"); 
   //pstmt.setint(2, 1); 
   //pstmt.setblob(1, new bytearrayinputstream("12345中国".getbytes())); 
   //pstmt.setint(2, 76732); 
   /*if(pstmt.executeupdate()>0){ 
    //system.out.println("更新id=1的数据成功!"); 
    system.out.println("更新id=76732的数据成功!"); 
   } 
   conn.commit();*/ 
    
   system.out.println("update t_wx_ltnrk success"); 
  } catch (sqlexception e) { 
   //logger.error("query entity list failure", e); 
   system.out.println("更新数据异常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失败"); 
    } 
   } 
    
   if(conn!=null){ 
    try { 
     conn.close(); 
    } catch (sqlexception e) { 
     // todo auto-generated catch block 
     e.printstacktrace(); 
    } 
   } 
   //移除线程里面的connection,不移除会导致connection关闭以后,获取的connection是 关闭状态,不能进行数据操作 
   connection_holder.remove(); 
   //closeconnection(); 
  } 
  //return entitylist; 
 } 
  
  
} 

9、基本的数据库连接池就创建完毕了,之后就可以通过databasehelper的update方法来模拟获取数据库连接进行数据库的操作,可根据自己的需求进行数据的操作。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网