開発では、DBCPデータベース接続プールなどのデータベース接続プールをよく使用します。この章では、Java接続DBCPデータベースライブラリ接続プールの簡単な使用について説明します。
開発ツールmyeclipse2014
1.最初にWebプロジェクトを作成します。プロジェクト名testjdbcという名前を付けました。サーブレットを構成するには、web.xmlを使用した構成ファイルが必要です。作成が完了した後、プロジェクト構造は次のとおりです。
2。パッケージを作成します。私が作成したパッケージ名はcom.szkingdom.dbです
3.ヘルプクラスのCastutilを作成します。コードは次のとおりです。
パッケージcom.szkingdom.db; /*** 2015/12/26にJackによって作成されました。 *変換操作ツールクラス*/パブリッククラスcastutil {/**文字列タイプに変換***/ public static string castString(object obj){return castutil.caststring(obj、 ""); } / * *文字列タイプに変換(デフォルト値を提供) string.valueof(obj):defaultValue; } / * *ダブルタイプに変換 * * * / public static double castdouble(object obj){return castdouble(obj、(double)0); } / * *ダブルタイプに変換(Devided Default Value) if(obj!= null){string strvalue = castString(obj); if(stringutil.isnotempty(strvalue)){try {doublevalue = double.parsedouble(strvalue); } catch(numberformatexception e){defaultValue = defaultValue; }}} doubleValueを返します。 } / * *長いタイプに変換 * * * / public static long castlong(object obj){return castlong(obj、0); } / * *長いタイプに変換(デフォルト値を提供) 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タイプに変換(デフォルト値を提供) 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); } / * * booleanタイプに変換(デフォルト値を提供) if(obj!= null){booleanvalue = boolean.parseboolean(caststring(obj)); } booleanvalueを返します。 }} 4.プロパティファイルを作成して、ヘルプクラスPropsutilを読むために、コードは次のとおりです。
パッケージcom.szkingdom.db; java.io.filenotfoundexceptionをインポートします。 java.io.ioexceptionをインポートします。 java.io.inputStreamをインポートします。 java.util.propertiesをインポートします。 /*** 2015/12/26にJackによって作成されました。 *プロパティファイルツールクラス*/public class propsutil {// private static final logger logger = loggerfactory.getLogger(propsutil.class); / * *プロパティファイルの読み込み * * */ public staticプロパティloadprops(string filename){プロパティプロパティ= null; inputstream inputstream = null; try {inputstream = thread.currentthread()。getContextClassLoader()。getResourceAsStream(filename); if(inputStream == null){新しいfilenotFoundException(filename + "ファイルが見つかりません!"); }プロパティ= new Properties(); properties.load(inputstream); } catch(ioException e){//logger.error("load properties file fails "、e); System.out.println( "ロードプロパティファイル障害:"+e); }最後に{if(inputstream!= null){try {inputstream.close(); } catch(ioException e){//logger.error("close入力ストリーム障害 "、e); System.out.println( "入力ストリームの閉鎖障害:"+e); }} return Properties; } / * *文字属性を取得します(デフォルトは空の文字列です) } / * * Chature-Type属性を取得します(デフォルト値を指定できます) if(props.containskey(key)){value = props.getProperty(key); } return値; } / * *数値型属性を取得(デフォルトは0) } / * *数値型属性を取得します(デフォルト値を指定できます) if(propss.containskey(key)){value = castutil.castint(props.getProperty(key)); } return値; } / * *ブールプロパティを取得します(デフォルト値はfalse) } / * * booleanプロパティを取得(デフォルト値を指定できます) if(propss.containskey(key)){value = castutil.castboolean(props.getProperty(key)); } return値; }} 5.文字列ヘルプクラスのstringutilを作成します。コードは次のとおりです。
パッケージcom.szkingdom.db; /*** 2015/12/26にJackによって作成されました。 * String Tool class */ public class stringutil {/ * *文字列が空であるかどうかを決定します * */ public static boolean isempty(string str){if(str!= null){str = str.trim(); } // stringutils.isempty(str)を返します。 return "" .equals(str); } / * *文字列が空でないかどうかを判断します * * / public static boolean isnotempty(string str){return!isempty(str); }} 6.データベース接続プロパティファイルdbconfig.propertiesをSRCディレクトリに作成する
<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、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; java.io.bytearrayinputStreamをインポートします。 Java.sql.Connectionをインポートします。 Java.sql.drivermanagerをインポートします。 Java.sql.preparedStatementをインポートします。 java.sql.resultsetをインポートします。 java.sql.sqlexceptionをインポートします。 java.util.propertiesをインポートします。 org.apache.commons.dbcp2.basicdatasourceをインポートします。 /*** 2015/12/26にJackによって作成されました。データベース操作アシスタントクラス*/ public class databasehelper {// private static final logger logger = // loggeractory.getLogger(databasehelper.class);プライベート静的ファイナルストリングドライバー。プライベート静的最終文字列URL;プライベート静的最終文字列ユーザー名。プライベート静的最終文字列パスワード。 // 1つのスレッドと1つの接続を確保します。 //スレッドプールプライベート静的最終basicDataSource data_source; static {connection_holder = new ThreadLocal <Connection>();プロパティconf = propsutil.loadprops( "dbconfig.properties"); driver = conf.getProperty( "jdbc.driver"); url = conf.getProperty( "jdbc.url"); username = conf.getProperty( "jdbc.username");パスワード= 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.itee.com/blog/1969273 //http://blog.csdn.net/j903829182/article/details/50190337 //http://blog.csdn.net/jiutianhe/article/details/39670817 //http://20983.683.683.th. //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); //タイムアウト待機時間milliseconds data_source.setmaxwaitmillis(2*10000); //現在の接続のみが無効です。現在のクエリがdata_source.settestonborrow(true)を使用するための別の接続を作成します。 // removeabandonedtimeout:未使用(不在)接続のリサイクル(デフォルトは300秒、180に調整されています)data_source.setRemoveaBandonedTimeout(180); // RemoveaBandoned:RemoveaBandonedTimeOutの時間をRemoveaBandonedTimeoutの時間を超えた後、未使用(不在)接続をリサイクルするかどうか(デフォルトはfalse、trueに調整されています) data_source.setRemoveaBandonedonBorrow(true); // data_source.settestonreturn(true); // testonreturn data_source.settestonreturn(true); // setRemoveabandonedonMaintenance data_source.setRemoveaBandonedonMantenance(true); // log log data_source.setlogabandeded(true); // SetAddress Automatic Submission Data_Source.setDefaultAutoCommit(true); // data_source.setEnableautocommitonreturn(true); system.out.println( "データベース接続のパラメーター設定を完了しますプールdata_source !!"); /*try {class.forname(driver); system.out.println( "JDBCドライバーの成功をロード"); } catch(classNotFoundException e){// logger.error( "JDBCドライバーをロードできない"、e); System.out.println( "JDBCドライバーをロードできない:" + e); }最後に{}*/} // 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( "接続成功を取得する"); } catch(sqlexception e){// logger.error( "接続障害を取得"、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( "Initial Size Intiallsize ="+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故障"、e); system.out.println( "接続障害の閉鎖:" + e);新しいruntimeexception(e); }最後に{connection_holder.remove(); }}} //データベース操作の実行public static同期Voidアップデート(int thlsh、string ltnr){connection conn = getConnection(); if(conn == null){system.out.println( "更新方法の()接続はnull !!"); } predStatement pstmt = null; system.out.println( "update start!"); int ltlsh = 0; try {// string sql = "メッセージを更新するコンテンツ=?where id =?"; // string sql1 = "lsh =?"からt_zxthlskからltlshを選択します。 "; string sql = "update t_wx_ltnrk b set b.ltnr =?where b.lsh ="+ "(t_zxthlsk a where a.lsh =?)"からa.ltlshを選択します。 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テスト2222"); pstmt.setint(2、6);*/if(pstmt.executeUpdate()> 0){//system.out.println("update data it with id = 1 ressectly! "); system.out.println( "thlsh ="+thlsh+"のチャットコンテンツデータを更新してください!/nチャットコンテンツは"+ltnr); } //conn.commit(); /*(while(rs1.next()){ltlsh = rs1.getint( "ltlsh"); system.out.println( "チャットフロー番号を正常にクエリすると、チャットフロー番号はltlsh->"+ltlsh); }*///pstmt.setString(1、 "優れたコンテンツ更新1"); //pstmt.setint(2、1); //pstmt.setblob(1、new bytearrayinputStream( "12345 China" .getBytes())); //pstmt.setint(2、76732); /* fif (pstmt.executeUpdate()> 0){//system.out.println("update data with id = 1 succude! "); System.out.println( "ID = 76732成功! } conn.commit();*/ system.out.println( "更新t_wx_ltnrk success"); } catch(sqlexception e){//logger.error("query entity list fails "、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 auto-enerated catch block e.printstacktrace(); system.out.println( "preated -statement failed"); }} if(conn!= null){try {conn.close(); } catch(sqlexception e){// todo auto-enerated catch block e.printstacktrace(); }} //スレッド内の接続を削除します。接続が削除されない場合、取得した接続が閉じられます。データ操作は実行できません。 connection_holder.remove(); // closeconnection(); } // return entityList; }} 9.基本的なデータベース接続プールが作成されます。その後、データベースヘルパーの更新方法を介してデータベース接続をシミュレートして、データベース接続を取得する操作をシミュレートし、自分のニーズに応じてデータ操作を実行できます。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。