相对JDBC(二) 增加c3p0连接池,封装DBUtil类,网上下载c3p0的包
public class DBUtil {
//数据库连接池对象
private static ComboPooledDataSource dataSource;
private static Properties props;
private static InputStream is;
static {
try {
//得到属性文件的输入流
//得到类加载器
ClassLoader cls = DBUtil.class.getClassLoader();
//通过类加载器获取类路径(classpath)下的资源
is = cls.getResourceAsStream("dbconfig.properties");
//创建Properties对象
props = new Properties();
//加载Properties文件数据
props.load(is);
//创建一个数据库连接对象
dataSource = new ComboPooledDataSource();
//设置数据库连接池的参数
//设置驱动类
dataSource.setDriverClass(props.getProperty("driverClass"));
//设置URL
dataSource.setJdbcUrl(props.getProperty("jdbcUrl"));
//设置用户名
dataSource.setUser(props.getProperty("user"));
//设置密码
dataSource.setPassword(props.getProperty("password"));
//设置初始化连接数量
dataSource.setInitialPoolSize(Integer.parseInt(props.getProperty("initialPoolSize")));
//设置最大连接数量
dataSource.setMaxPoolSize(Integer.parseInt(props.getProperty("maxPoolSize")));
//设置最小连接数量
dataSource.setMinPoolSize(Integer.parseInt(props.getProperty("minPoolSize")));
//设置连接的最大闲置时间
dataSource.setMaxIdleTime(Integer.parseInt(props.getProperty("maxIdleTime")));
//设置每次获取新连接的个数
dataSource.setAcquireIncrement(Integer.parseInt(props.getProperty("acquireIncrement")));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取连接
*
* @return
*/
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 关闭连接
*
* @param rs
* @param stm
* @param conn
*/
public static void close(ResultSet rs, Statement stm, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
需要src目录下新建dbconfig.properties,这样当比如用户密码改动就不需要去改动类文件了,只需改动dbconfig.properties里面的配置参数就行。下面是文件内容。
driverClass=oracle.jdbc.OracleDriver
jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
user=scott
password=pan
initialPoolSize=5
maxPoolSize=20
minPoolSize=5
maxIdleTime=200
acquireIncrement=3