c3p0資料庫連接池dbutil

來源:互聯網
上載者:User
package cn.secondteam.utils;import java.beans.PropertyVetoException;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import com.mchange.v2.c3p0.ComboPooledDataSource;public class DbUtil {final static String HOST = "127.0.0.1";final static String NAME = "root";final static String PSW = "root";static final String DBNAME = "bbsdb";private static Connection connection;public static ComboPooledDataSource dsWebgame;static {dsWebgame = new ComboPooledDataSource();               try {                  dsWebgame.setDriverClass(DRIVER);               } catch (PropertyVetoException e) {                  e.printStackTrace();              }               // 參數由 Config 類根據設定檔讀取              dsWebgame.setJdbcUrl(URL);             // 設定資料庫的登入使用者名稱             dsWebgame.setUser(USERNAME);             // 設定資料庫的登入使用者密碼             dsWebgame.setPassword(PASSWORD);             // 設定串連池的最大串連數             dsWebgame.setMaxPoolSize(35);             // 設定串連池的最小串連數             dsWebgame.setMinPoolSize(20);             // 有時候會產生死結,將maxStatements設定為0             dsWebgame.setMaxStatements(0);             //小於MySQL的wait timeout即可。              dsWebgame.setIdleConnectionTestPeriod(120);}/** * 擷取資料庫連接 *  * @return */public static  Connection getConnection() {              if (null == connection) {                 connection=newConnection();              }               try {                 if(connection.isClosed()){                    connection=dsWebgame.getConnection();                }             } catch (SQLException e) {                e.printStackTrace();             }             return connection;        }/** * 建立資料庫連接 * @return */private static Connection newConnection() {try {return (Connection) dsWebgame.getConnection();} catch (SQLException e) {e.printStackTrace();return null;}}public static void main(String args[]){getConnection();}/** * 釋放資源 * @param conn * @param st * @param rs */public static void release(Connection con, Statement st, ResultSet rs) {if (rs != null) {try {rs.close();} catch (Exception e) {e.printStackTrace();}rs = null;}if (st != null) {try {st.close();} catch (Exception e) {e.printStackTrace();}}if (con != null) {try {con.close();} catch (Exception e) {e.printStackTrace();}}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.