boolean flag = false; PreparedStatement ps; ResultSet rs; try { String sql = "select * from usr where username = ? and password = ?"; ps = DBconn.getConn().prepareStatement(sql); ps.setString(1, username); ps.setString(2, password); rs = ps.executeQuery(sql);如何避免其中rs为null
时间: 2023-11-28 19:49:27 浏览: 83
在执行 `rs = ps.executeQuery(sql);` 时,如果查询结果为空,`rs` 不会为 `null`,而是返回一个空的 `ResultSet` 对象,因此我们需要使用 `rs.next()` 判断是否有查询结果。
可以改写为如下代码:
```
boolean flag = false;
PreparedStatement ps;
ResultSet rs;
try {
String sql = "select * from usr where username = ? and password = ?";
ps = DBconn.getConn().prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery(); // 不需要再传入 sql 参数
if (rs.next()) { // 判断是否有查询结果
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
DBconn.closeConn();
}
```
这样就可以避免 `rs` 为 `null` 的情况了。
阅读全文
相关推荐
![](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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)