在开发中中我们经常会使用到数据库连接池,比如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://mit();*/ 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方法来模拟获取数据库连接进行数据库的操作,可根据自己的需求进行数据的操作。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。