개발 중에는 종종 DBCP 데이터베이스 연결 풀과 같은 데이터베이스 연결 풀을 사용합니다. 이 장에서는 Java Connection DBCP 데이터베이스 라이브러리 연결 풀의 간단한 사용에 대해 설명합니다.
개발 도구 MyClipse2014
1. 먼저 웹 프로젝트를 만듭니다. 나는 프로젝트 이름 testjdbc를 지명했습니다. 서블릿을 구성하려면 web.xml로 구성 파일이 필요합니다. 생성이 완료된 후 프로젝트 구조는 다음과 같습니다.
2. 패키지를 만듭니다. 내가 만든 패키지 이름은 com.szkingdom.db입니다
3. 도움말 클래스 Castutil을 만들면 코드는 다음과 같습니다.
패키지 com.szkingdom.db; /*** 2015/12/26에 Jack에 의해 만들어졌습니다. * 변환 작업 도구 클래스*/ public class castUtil {/** 문자열 유형으로 변환**/ public static string caststring (object obj) {return castutil.caststring (obj, ""); } / * * 문자열 유형 (기본값 제공) * / public static String castString (개체 obj, 문자열 기본값) {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; }} 반환 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; } / * * 부울 유형으로 변환 * * / 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)); } 반환 booleanValue; }} 4. Help Class Propsutil을 읽을 속성 파일을 작성하십시오. 코드는 다음과 같습니다.
패키지 com.szkingdom.db; import java.io.filenotfoundException; import java.io.ioexception; import java.io.inputstream; java.util.properties import; /*** 2015/12/26에 Jack에 의해 만들어졌습니다. * 속성 파일 도구 클래스*/public class propsutil {// private static final logger = loggerfactory.getLogger (propsutil.class); / * * 속성 파일로드 * * */ public static properties loadProps (String filename) {속성 속성 = null; inputStream inputStream = null; try {inputStream = thread.currentThread (). getContextClassLoader (). getResourCeasStream (filename); if (inputStream == null) {새 FilenotFoundException (filename + "파일을 찾을 수 없습니다!"); } 특성 = 새로운 속성 (); 속성 .LOAD (inputStream); } catch (ioexception e) {//logger.error("load 속성 파일 실패 ", e); System.out.println ( "로드 속성 파일 실패 :"+e); } 마침내 {if (inputStream! = null) {try {inputStream.close (); } catch (ioexception e) {//logger.error("Close Input Stream Failure ", e); System.out.println ( "닫기 입력 스트림 실패 :"+e); }} 반환 속성; } / * * 문자 속성 가져옵니다 (기본값은 빈 문자열입니다) * * * / public static string getstring (속성, 문자열 키) {return getString (props, key, ""); } / * * 문자 유형 속성 가져 오기 (기본값을 지정할 수 있음) * / public static string getstring (속성 소품, 문자열 키, 문자열 기본값) {문자열 값 = defaultValue; if (props.containskey (key)) {value = props.getProperty (키); } 반환 값; } / * * 숫자 유형 속성 가져 오기 (기본값은 0) * * / public static int getInt (속성 소품, 문자열 키) {return getInt (props, key, 0); } / * * 숫자 유형 속성을 가져옵니다 (기본값을 지정할 수 있음) * / public static int getInt (속성 소품, 문자열 키, int defaultValue) {int value = defaultValue; if (props.containskey (key)) {value = castutil.castint (props.getProperty (key)); } 반환 값; } / * * 부울 속성을 가져옵니다 (기본값은 false) * * / public static boolean getBoolean (속성 소품, 문자열 키) {return getBoolean (props, key, false); } / * * 부울 속성 가져 오기 (기본값을 지정할 수 있음) * * / public static boolean getBoolean (속성 소품, 문자열 키, 부울 기본값) {boolean value = defaultValue; if (props.containskey (key)) {value = castutil.castboolean (propss.getProperty (key)); } 반환 값; }} 5. 문자열을 만듭니다. class stringUtil, 코드는 다음과 같습니다.
패키지 com.szkingdom.db; /*** 2015/12/26에 Jack에 의해 만들어졌습니다. * 문자열 도구 클래스 */ public class stringUtil {/ * * 문자열이 비어 있는지 결정 */ public static boolean isempty (string str) {if (str! = null) {str = str.trim (); } // return stringUtils.isempty (str); 반환 "".Equals (str); } / * * 문자열이 비어 있지 않은지 결정 * / public static boolean is nontempty (String str) {return! isempty (str); }} 6. 데이터베이스 연결 속성 파일 생성 SRC 디렉토리의 프로파인 티.
<span style = "색상 :#333333;"> jdbc.driver = com.mysql.jdbc.driver jdbc.url = jdbc : mysql : // </span> <span style = "색상 :#ff6666; 배경 색 : rgb (255, 0, 0); ">"> 127.0.0.1:3306/****</span><<<<<<<<span style = "color :#333333;"> jdbc.username = **** jdbc.password = **** </span>
7. 필요한 JAR 패키지를 LIB 디렉토리에 넣으십시오.
8. DBCP를 사용하여 데이터베이스 도움말 클래스를 만듭니다
패키지 com.szkingdom.db; import java.io.bytearrayinputstream; java.sql.connection 가져 오기; Java.SQL.DriverManager 가져 오기; Java.sql.preparedStatement import; java.sql.resultset import; java.sql.sqlexception 가져 오기; java.util.properties import; import org.apache.commons.dbcp2.basicdatasource; /*** 2015/12/26에 Jack에 의해 만들어졌습니다. 데이터베이스 운영 어시스턴트 클래스*/ public class databaseHelper {// private static final logger = // loggerFactory.getLogger (databaseHelper.class); 개인 정적 최종 문자열 드라이버; 개인 정적 최종 문자열 URL; 개인 정적 최종 문자열 사용자 이름; 비공개 정적 최종 문자열 암호; // 하나의 스레드와 하나의 연결을 보장합니다. 스레드-세이프 개인 정적 최종 최종 STREADLOCAL <Confeint> Connection_holder; // 스레드 풀 개인 정적 최종 최종 최종 DataSource Data_Source; static {connection_holder = new ThreadLocal <connection> (); 속성 conf = propsutil.loadprops ( "dbconfig.properties"); 드라이버 = conf.getProperty ( "jdbc.driver"); url = conf.getProperty ( "jdbc.url"); username = conf.getProperty ( "jdbc.username"); password = conf.getProperty ( "jdbc.password"); 문자열 드라이버 = conf.getProperty ( "jdbc.driver"); 문자열 url = conf.getProperty ( "jdbc.url"); 문자열 username = conf.getProperty ( "jdbc.username"); String PassWrod = conf.getProperty ( "jdbc.password"); data_source = new Basicdatasource (); data_source.setdriverclassName (드라이버); data_source.seturl (url); data_source.setusername (사용자 이름); 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/jiutianhee/article/details/39670817 //http://bsr1983 //http://blog.csdn.net/kerafan/article/details/50382998 //http://blog.csdn.net/a9529lty/article/details/43021801 /// 433021801 /// 유휴 시점과 동일 시간에 활성화 될 수 있습니다. data_source.setmaxtotal (60); // 초기 크기를 설정합니다. data_source.setInitialSize (10); // 최소 유휴 연결 데이터 _source.setminidle (8); // 최대 유휴 연결 Data_Source.setMaxIdle (16); // 타임 아웃 대기 시간 밀리 초 밀리 초 데이터 _source.setmaxwaitmillis (2*10000); // 현재 연결 만 유효하지 않습니다. 현재 쿼리가 Data_Source.SetTestOnbrong (true)을 사용하려는 다른 연결을 만듭니다. // removeaBandOnEdTimeout : 재활용 미사용 (결석) 연결 (기본값은 300 초, 180으로 조정 됨) Data_Source.SetRemoveAbandonEdTimeout (180); // removeAbandoned : 제거 시간이 제거 된 후 제거 시간이 제거 시간을 초과 한 후, 미사용 (결석) 연결을 재활용할지 여부 (기본값은 거짓, true로 조정 됨) //data_source.setRemoveAbandonEdonMainenagement (removeaandonedonedonMainenagement); data_source.setRemoveaBandonEdonBorrow (true); // testwhileIdle data_source.setTestOnreturn (true); // testOnreturn data_source.settestonreturn (true); // setRemoveaBandonEdonMainenage Data_Source.SetRemoveAbenOnedOnMainGent (true); // 레코드 로그 data_source.setLogAbandoned (true); // setAddress 자동 제출 data_source.setDefaultAutoCommit (true); // data_source.setenableautocommitonreturn (true); System.out.println ( "데이터베이스 연결 풀 데이터 _source !!의 매개 변수 설정을 완료하십시오!"); /*try {class.forname (드라이버); System.out.println ( "JDBC 드라이버 성공을로드"); } catch (classNotFoundException e) {// logger.error ( "JDBC 드라이버를로드 할 수 없음", e); System.out.println ( "JDBC 드라이버를로드 할 수 없습니다 :" + e); } 마침내 {}*/} // private static finallocal <connection> connection_holder = new ThreadLocal <conn /*** 데이터베이스 연결 가져옵니다*/public static connection getConnection () {Connection connest = connection_holder.get (); // 1 if (conn == null) {try {// conn = drivermanager.getConnection (url, username, password); conn = data_source.getConnection (); System.out.println ( "연결 성공 GET"); } catch (sqlexception e) {// logger.error ( "연결 실패 get", e); System.out.println ( "연결 실패 :" + E); } 마지막으로 {/*system.out.println ( "최소 유휴 연결 Minidle ="+data_source.getMinidle ()); System.out.println ( "MaxIdle Connection MaxIdle ="+data_source.getMaxIdle ()); System.out.println ( "최대 연결 수 Maxtotal ="+data_source.getmaxtotal ()); System.out.println ( "초기 크기 이니셜 크기 ="+data_source.getInitialSize ()); System.out.println ( "시간 초과 대기 시간 MaxWaitMillis ="+(data_source.getMaxwaitMillis ()/1000)); System.out.println ( "활성 연결 GET getNumActive () ="+data_source.getNumactive ()); System.out.println ( "연결 수를 가져옵니다 getNumidle ="+data_source.getnumidle ());*/ connection_holder.set (conn); }} return conn; }/ *** 데이터베이스 연결을 닫습니다*/ public static void closeConnection () {Connection Conness = Connection_holder.get (); // 1 if (conn! = null) {try {conn.close (); System.out.println ( "Close Connection Success"); } catch (sqlexception e) {// logger.error ( "닫기 실패", e); System.out.println ( "연결 실패 :" + E); 새로운 runtimeexception (e)을 던지십시오. } 마침내 {connection_holder.remove (); }}} // 데이터베이스 작업 수행 공개 정적 동기화 된 무효 업데이트 (int thlsh, String ltnr) {Connection Conn = getConnection (); if (conn == null) {system.out.println ( "업데이트 메소드의 () 연결은 null !!"); } proadstatement pstmt = null; System.out.println ( "업데이트 시작!"); int ltlsh = 0; try {// string sql = "메시지 세트 업데이트 내용 =? where id =?"; // String sql1 = "t_zxthlsk에서 ltlsh를 선택하여 lsh =?"; 문자열 sql = "업데이트 t_wx_ltnrk b set b.ltnr =? b.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, "이것은 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, "우수한 컨텐츠 업데이트"); //pstmt.setint(2, 1); //pstmt.setBlob(1, New BytearRayInputStream ( "12345 China".getBytes ()); //pstmt.setint(2, 76732); /*if(pstmt.executeUpdate ()> 0) {//system.out.println("update data id = 1 success! "); System.out.println ( "ID = 76732 성공한 데이터 업데이트!"); } conn.commit ();*/ system.out.println ( "T_WX_LTNRK 성공 업데이트"); } catch (sqlexception e) {//logger.error("Query Entity List Obfarent ", e); System.out.println ( "데이터 예외 업데이트 Connection ="+Conn); System.out.println ( "T_WX_LTNRK 실패 업데이트 :" + E); 새로운 runtimeexception (e)을 던지십시오. } 마침내 {// closeConnection (); // closeConnection (); if (pstmt! = null) {try {pstmt.close (); } catch (sqlexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); System.out.println ( "준비 상태 실패"); }} if (conn! = null) {try {conn.close (); } catch (sqlexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }} // 스레드에서 연결을 제거합니다. 연결이 제거되지 않으면 획득 된 연결이 닫힙니다. 데이터 작동을 수행 할 수 없습니다. Connection_holder.remove (); // closeConnection (); } // entityList를 반환합니다. }} 9. 기본 데이터베이스 연결 풀이 생성됩니다. 그런 다음 DatabaseHelper의 업데이트 방법을 통해 데이터베이스 연결을 시뮬레이션하여 데이터베이스 연결을 얻는 작업을 시뮬레이션하고 자신의 요구에 따라 데이터 작업을 수행 할 수 있습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.