栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java使用dbcp2数据库连接池

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java使用dbcp2数据库连接池

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

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

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

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

package com.szkingdom.db; 
 
public class CastUtil { 
   
  public static String castString(Object obj) { 
   return CastUtil.castString(obj, ""); 
  } 
  
   
  public static String castString(Object obj, String defaultValue) { 
   return obj != null ? String.valueOf(obj) : defaultValue; 
  } 
  
   
  public static double castDouble(Object obj) { 
   return castDouble(obj, (double)0); 
  } 
  
   
  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; 
  } 
  
   
  public static long castLong(Object obj) { 
   return castLong(obj, 0); 
  } 
  
   
  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; 
  } 
  
   
  public static int castInt(Object obj){ 
   return castInt(obj,0); 
  } 
   
  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; 
  } 
  
   
  public static boolean castBoolean(Object obj){ 
   return castBoolean(obj,false); 
  } 
   
  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; 
 
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; 
  } 
  
   
  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; 
  } 
  
   
  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; 
 
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

jdbc.driver=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://127.0.0.1:3306 
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_HOLDER ; 
 //线程池 
 private static final BasicDataSource DATA_SOURCE; 
 static { 
   CONNECTION_HOLDER = new ThreadLocal(); 
   
  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的参数!!"); 
   
 } 
 //private static final ThreadLocal CONNECTION_HOLDER = new ThreadLocal(); 
 
  
 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 { 
     
    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); 
    
   if(pstmt.executeUpdate()>0){ 
    //System.out.println("更新id=1的数据成功!"); 
    System.out.println("更新thlsh="+thlsh+"的聊天内容数据成功!n聊天内容为:"+ltnr); 
   } 
   //conn.commit(); 
    
    
    
   //pstmt.setString(1, "精彩内容update1"); 
   //pstmt.setInt(2, 1); 
   //pstmt.setBlob(1, new ByteArrayInputStream("12345中国".getBytes())); 
   //pstmt.setInt(2, 76732); 
    
    
   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方法来模拟获取数据库连接进行数据库的操作,可根据自己的需求进行数据的操作。

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/148877.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号