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();}}}}