java應用dbcp2數據庫銜接池。本站提示廣大學習愛好者:(java應用dbcp2數據庫銜接池)文章只能為提供參考,不一定能成為您想要的結果。以下是java應用dbcp2數據庫銜接池正文
在開辟中中我們常常會應用到數據庫銜接池,好比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 >jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://</span><span >127.0.0.1:3306/****</span><span > 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辦法來模仿獲得數據庫銜接停止數據庫的操作,可依據本身的需求停止數據的操作。
以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。