logger.error("Failed to update user login status", e);添加关闭数据库的代码
时间: 2024-02-11 07:05:46 浏览: 20
在使用完数据库连接后,需要将连接关闭以释放资源。可以在try-with-resources语句中使用自动关闭资源的特性,将Connection对象放在try语句括号中。以下是添加关闭数据库连接的代码:
```java
String UPDATE_SQL = "update User_ZC set Login=? where UserId=?";
int count = 0;
try (Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(UPDATE_SQL)) {
pstmt.setInt(1, 1);
pstmt.setString(2, usernum);
count = pstmt.executeUpdate();
} catch (SQLException e) {
logger.error("Failed to update user login status", e);
}
// 关闭数据库连接
finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
logger.error("Failed to close database connection", e);
}
}
if (count > 0) {
request.getRequestDispatcher("ZCS.jsp").forward(request, response);
} else {
System.out.print("登陆失败");
}
```
需要注意的是,当数据库连接池的实现替换为使用JNDI获取连接池时,不需要手动关闭数据库连接,连接池会自动管理连接的生命周期。