jdbc
数据库连接池
dbcp连接池
需要两个包commons-dbcp-1.3,commons-pool-1.56
public class DbcpUtil {
private static final Logger logger = LoggerFactory.getLogger(JdbcUtil.class);
private static DataSource dataSource;
//静态代码块 防止多次加载驱动减小开销
static {
Properties p = new Properties();
try {
ClassLoader c = Thread.currentThread().getContextClassLoader();
InputStream inputStream = c.getResourceAsStream("dbcp.properties");
if (inputStream == null) {
throw new FileNotFoundException("dbcp.properties文件未找到");
}
p.load(inputStream);
dataSource = BasicDataSourceFactory.createDataSource(p);
} catch (Exception e) {
throw new RuntimeException("dbcp.properties读取失败", e);
}
}
/**
* 获取数据库连接对象
*
* @return
*/
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("数据库连接失败", e);
}
}
public static void close(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
logger.error("数据库关闭失败", e);
}
}
}
}
druid连接池
需要一个包druid-1.1.10
public class DbcpUtil {
private static final Logger logger = LoggerFactory.getLogger(JdbcUtil.class);
private static DataSource dataSource;
//静态代码块 防止多次加载驱动减小开销
static {
Properties p = new Properties();
try {
ClassLoader c = Thread.currentThread().getContextClassLoader();
InputStream inputStream = c.getResourceAsStream("dbcp.properties");
if (inputStream == null) {
throw new FileNotFoundException("dbcp.properties文件未找到");
}
p.load(inputStream);
dataSource = DruidDataSourceFactory.createDataSource(p);
} catch (Exception e) {
throw new RuntimeException("dbcp.properties读取失败", e);
}
}
/**
* 获取数据库连接对象
*
* @return
*/
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("数据库连接失败", e);
}
}
public static void close(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
logger.error("数据库关闭失败", e);
}
}
}
}