==作者:YB-Chi==
创建一个jdbc.propertis文件,其内容如下:
1 2 3 4 5 6
| driverClass = com.mysql.jdbc.Driver jdbcUrl = jdbc:mysql: user = root password = mysqladmin maxPoolSize = 20 minPoolSize = 5
|
创建一个MyDataBaseSource的枚举:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| import java.sql.Connection; import java.sql.SQLException; import java.util.ResourceBundle;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public enum MyDataBaseSource { DATASOURCE; private ComboPooledDataSource cpds = null;
private MyDataBaseSource() { try {
ResourceBundle rs = ResourceBundle.getBundle("jdbc"); cpds = new ComboPooledDataSource(); cpds.setDriverClass(rs.getString("driverClass")); cpds.setJdbcUrl(rs.getString("jdbcUrl")); cpds.setUser(rs.getString("user")); cpds.setPassword(rs.getString("password")); cpds.setMaxPoolSize(Integer.parseInt(rs.getString("maxPoolSize"))); cpds.setMinPoolSize(Integer.parseInt(rs.getString("minPoolSize"))); System.out.println("-----调用了构造方法------");
} catch (Exception e) { e.printStackTrace(); } }
public Connection getConnection() { try { return cpds.getConnection(); } catch (SQLException e) { return null; } }
}
|
测试代码:
1 2 3 4 5 6 7
| public class Test { public static void main(String[] args) { MyDataBaseSource.DATASOURCE.getConnection() ; MyDataBaseSource.DATASOURCE.getConnection() ; MyDataBaseSource.DATASOURCE.getConnection() ; } }
|
结果如下:
1 2 3
| -----调用了构造方法------ 2013-7-17 17:10:57 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager 信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge16d8v1tgb0wppydrzz|2c1e6b, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge16d8v1tgb0wppydrzz|2c1e6b, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql:
|
很显然获得了三个Connection连接,但是只调用了一次枚举的构造方法,从而通过枚举实现了单例的设计