在java中关闭数据库
时间: 2023-11-09 22:08:46 浏览: 27
连接的几种方式:
1. 使用try-with-resources语句自动关闭连接
```java
try (Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();) {
//执行SQL语句
} catch (SQLException e) {
e.printStackTrace();
}
```
2. 在finally语句块中手动关闭连接
```java
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
//执行SQL语句
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
3. 使用连接池管理连接,无需手动关闭连接
```java
//创建连接池
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driverClass);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
//从连接池获取连接
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
//执行SQL语句
//将连接归还给连接池
conn.close();
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)