packageutil;importjava.io.IOException;importjava.io.InputStream;importjava.sql.Connection;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;importjava.util.Properties;importorg.apache.commons.dbcp.BasicDataSource;public classDBUtils {private staticBasicDataSource dataSource;static{//读取属性配置文件
Properties prop = newProperties();//得到文件输入流
InputStream ips = DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");//把文件流加载到prop对象中
try{
prop.load(ips);
String driver= prop.getProperty("driver");
String url= prop.getProperty("url");
String username= prop.getProperty("username");
String password= prop.getProperty("password");
String initSize= prop.getProperty("initialSize");
String maxSize= prop.getProperty("maxActive");//创建连接池数据源对象
dataSource = newBasicDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);//设置连接池策略信息
dataSource.setInitialSize(Integer.parseInt(initSize));
dataSource.setMaxActive(Integer.parseInt(maxSize));
}catch(IOException e) {
e.printStackTrace();
}
}public static Connection getConn() throwsSQLException{returndataSource.getConnection();
}public static void close(Connection conn,Statement stat,ResultSet rs) throwsSQLException {if(rs != null) {try{
rs.close();
}catch(SQLException e) {
e.printStackTrace();throwe;
}
}if(stat != null) {try{
stat.close();
}catch(SQLException e) {
e.printStackTrace();throwe;
}
}if(conn != null) {try{
conn.close();
}catch(SQLException e) {
e.printStackTrace();throwe;
}
}
}
}