try { String sql; sql = "SELECT name,password FROM table1 where name='"+name1+"' and password='"+password1+"'"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ String name = rs.getString("name"); String password = rs.getString("password"); if(name1.equals(name)&password1.equals(password)) { response.sendRedirect("Success.html"); return; } else { response.sendRedirect("DLSB.html"); return; } } rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { } 这段代码哪里有错,具体改正方式
时间: 2024-01-29 22:01:58 浏览: 30
这段代码中的问题可能是在执行SQL查询时没有正确地关闭资源,导致内存泄漏。正确地关闭资源可以使用try-with-resources语句,如下所示:
```java
try (Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
String name = rs.getString("name");
String password = rs.getString("password");
if (name1.equals(name) & password1.equals(password)) {
response.sendRedirect("Success.html");
return;
} else {
response.sendRedirect("DLSB.html");
return;
}
}
} catch (SQLException e) {
// 处理异常
}
```
在try-with-resources语句中,资源会在语句结束时自动关闭,无需手动关闭。另外,代码中的字符串比较应该使用equals方法而不是&运算符。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)