java使用dbcp2數(shù)據(jù)庫連接池
在開發(fā)中中我們經(jīng)常會(huì)使用到數(shù)據(jù)庫連接池,比如dbcp數(shù)據(jù)庫連接池,本章將講解java連接dbcp數(shù)據(jù)庫庫連接池的簡(jiǎn)單使用。
開發(fā)工具myeclipse2014
1、首先創(chuàng)建一個(gè)web項(xiàng)目,我把項(xiàng)目名取名為testjdbc,需要帶有web.xml的配置文件,進(jìn)行servlet的配置,創(chuàng)建完成以后的項(xiàng)目結(jié)構(gòu)如下:
2、創(chuàng)建包,我創(chuàng)建的包名是com.szkingdom.db
3、創(chuàng)建幫助類CastUtil,代碼如下:
package com.szkingdom.db; /** * Created by jack on 2015/12/26. * 轉(zhuǎn)型操作工具類 */ public class CastUtil { /* * 轉(zhuǎn)為String型 * */ public static String castString(Object obj) { return CastUtil.castString(obj, ""); } /* * 轉(zhuǎn)為String型(提供默認(rèn)值) * */ public static String castString(Object obj, String defaultValue) { return obj != null ? String.valueOf(obj) : defaultValue; } /* * 轉(zhuǎn)為double型 * */ public static double castDouble(Object obj) { return castDouble(obj, (double)0); } /* * 轉(zhuǎn)為double型(提供默認(rèn)值) * */ 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; } /* * 轉(zhuǎn)為long型 * */ public static long castLong(Object obj) { return castLong(obj, 0); } /* * 轉(zhuǎn)為long型(提供默認(rèn)值) * */ 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; } /* * 轉(zhuǎn)為int型 * */ public static int castInt(Object obj){ return castInt(obj,0); } /* * 轉(zhuǎn)為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; } /* * 轉(zhuǎn)為boolean型 * */ public static boolean castBoolean(Object obj){ return castBoolean(obj,false); } /* * 轉(zhuǎn)為boolean型(提供默認(rèn)值) * */ public static boolean castBoolean(Object obj,boolean defaultValue){ boolean booleanValue=defaultValue; if(obj!=null){ booleanValue=Boolean.parseBoolean(castString(obj)); } return booleanValue; } }
4、創(chuàng)建屬性文件讀取幫助類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; } /* * 獲取字符型屬性(默認(rèn)為空字符串) * * */ public static String getString(Properties props, String key) { return getString(props, key, ""); } /* * 獲取字符型屬性(可指定默認(rèn)值) * */ public static String getString(Properties props, String key, String defaultValue) { String value = defaultValue; if (props.containsKey(key)) { value = props.getProperty(key); } return value; } /* * 獲取數(shù)值類型屬性(默認(rèn)為0) * */ public static int getInt(Properties props, String key) { return getInt(props, key, 0); } /* * 獲取數(shù)值類型屬性(可指定默認(rèn)值) * */ 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; } /* * 獲取布爾型屬性(默認(rèn)值為false) * */ public static boolean getBoolean(Properties props, String key) { return getBoolean(props, key, false); } /* * 獲取布爾型屬性(可指定默認(rèn)值) * */ 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、創(chuàng)建一個(gè)字符串幫助類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目錄下創(chuàng)建一個(gè)數(shù)據(jù)庫連接的屬性文件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創(chuàng)建數(shù)據(jù)庫幫助類
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. 數(shù)據(jù)庫操作助手類 */ 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; //保證一個(gè)線程一個(gè)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); //數(shù)據(jù)庫連接池參數(shù)配置: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 ///設(shè)置空閑和借用的連接的最大總數(shù)量,同時(shí)可以激活。 DATA_SOURCE.setMaxTotal(60); //設(shè)置初始大小 DATA_SOURCE.setInitialSize(10); //最小空閑連接 DATA_SOURCE.setMinIdle(8); //最大空閑連接 DATA_SOURCE.setMaxIdle(16); //超時(shí)等待時(shí)間毫秒 DATA_SOURCE.setMaxWaitMillis(2*10000); //只會(huì)發(fā)現(xiàn)當(dāng)前連接失效,再創(chuàng)建一個(gè)連接供當(dāng)前查詢使用 DATA_SOURCE.setTestOnBorrow(true); //removeAbandonedTimeout :超過時(shí)間限制,回收沒有用(廢棄)的連接(默認(rèn)為 300秒,調(diào)整為180) DATA_SOURCE.setRemoveAbandonedTimeout(180); //removeAbandoned :超過removeAbandonedTimeout時(shí)間后,是否進(jìn) 行沒用連接(廢棄)的回收(默認(rèn)為false,調(diào)整為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); //設(shè)置自動(dòng)提交 DATA_SOURCE.setDefaultAutoCommit(true); // DATA_SOURCE.setEnableAutoCommitOnReturn(true); System.out.println("完成設(shè)置數(shù)據(jù)庫連接池DATA_SOURCE的參數(shù)??!"); /*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>(); /** * 獲取數(shù)據(jù)庫連接 */ 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(" 最大連接數(shù)量MaxTotal="+DATA_SOURCE.getMaxTotal()); System.out.println(" 初始大小InitialSize="+DATA_SOURCE.getInitialSize()); System.out.println(" 超時(shí)等待時(shí)間MaxWaitMillis="+(DATA_SOURCE.getMaxWaitMillis()/1000)); System.out.println(" 獲取活動(dòng)的連接數(shù)getNumActive()="+DATA_SOURCE.getNumActive()); System.out.println(" 獲取連接數(shù)getNumIdle="+DATA_SOURCE.getNumIdle());*/ CONNECTION_HOLDER.set(conn); } } return conn; } /** * 關(guān)閉數(shù)據(jù)庫連接 */ 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(); } } } //進(jìn)行數(shù)據(jù)庫操作 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的數(shù)據(jù)成功!"); System.out.println("更新thlsh="+thlsh+"的聊天內(nèi)容數(shù)據(jù)成功!\n聊天內(nèi)容為:"+ltnr); } //conn.commit(); /*while(rs1.next()){ ltlsh = rs1.getInt("ltlsh"); System.out.println("查詢聊天流水號(hào)成功,聊天流水號(hào)為ltlsh->"+ltlsh); }*/ //pstmt.setString(1, "精彩內(nèi)容update1"); //pstmt.setInt(2, 1); //pstmt.setBlob(1, new ByteArrayInputStream("12345中國(guó)".getBytes())); //pstmt.setInt(2, 76732); /*if(pstmt.executeUpdate()>0){ //System.out.println("更新id=1的數(shù)據(jù)成功!"); System.out.println("更新id=76732的數(shù)據(jù)成功!"); } conn.commit();*/ System.out.println("update t_wx_ltnrk success"); } catch (SQLException e) { //LOGGER.error("query entity list failure", e); System.out.println("更新數(shù)據(jù)異常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,不移除會(huì)導(dǎo)致connection關(guān)閉以后,獲取的connection是 關(guān)閉狀態(tài),不能進(jìn)行數(shù)據(jù)操作 CONNECTION_HOLDER.remove(); //closeConnection(); } //return entityList; } }
9、基本的數(shù)據(jù)庫連接池就創(chuàng)建完畢了,之后就可以通過DatabaseHelper的update方法來模擬獲取數(shù)據(jù)庫連接進(jìn)行數(shù)據(jù)庫的操作,可根據(jù)自己的需求進(jìn)行數(shù)據(jù)的操作。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java正則表達(dá)式匹配字符串并提取中間值的方法實(shí)例
正則表達(dá)式常用于字符串處理、表單驗(yàn)證等場(chǎng)合,實(shí)用高效,下面這篇文章主要給大家介紹了關(guān)于Java正則表達(dá)式匹配字符串并提取中間值的相關(guān)資料,需要的朋友可以參考下2022-06-06maven項(xiàng)目pom.xml中parent標(biāo)簽的使用小結(jié)
使用maven是為了更好的幫項(xiàng)目管理包依賴,maven的核心就是pom.xml,當(dāng)我們需要引入一個(gè)jar包時(shí),在pom文件中加上就可以從倉庫中依賴到相應(yīng)的jar包,本文就來介紹一下maven項(xiàng)目pom.xml中parent標(biāo)簽的使用小結(jié),感興趣的可以了解一下2023-12-12Java正則表達(dá)式_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
什么是正則表達(dá)式,正則表達(dá)式的作用是什么?這篇文章主要為大家詳細(xì)介紹了Java正則表達(dá)式的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05Java數(shù)據(jù)結(jié)構(gòu)及算法實(shí)例:冒泡排序 Bubble Sort
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)及算法實(shí)例:冒泡排序 Bubble Sort,本文直接給出實(shí)現(xiàn)代碼,代碼中包含詳細(xì)注釋,需要的朋友可以參考下2015-06-06SpringBoot整合MybatisSQL過濾@Intercepts的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot整合MybatisSQL過濾@Intercepts的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03spring boot hutool整合email的詳細(xì)過程
這篇文章主要介紹了spring boot hutool整合email的相關(guān)知識(shí),本文介紹兩種方式發(fā)送email文件,結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03Java中l(wèi)ambda表達(dá)式的基本運(yùn)用
大家好,本篇文章主要講的是Java中l(wèi)ambda表達(dá)式的基本運(yùn)用,感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下2022-01-01