UserDaoImpl.java:public boolean login(String username, String password) { boolean flag = false; try { DBconn.init(); ResultSet rs ; rs = DBconn.selectSql("select * from usr where username='"+username+"' and password='"+password+"'"); while(rs.next()){ if(rs.getString("username").equals(username) && rs.getString("password").equals(password)){ flag = true; } } DBconn.closeConn(); } catch (SQLException e) { e.printStackTrace(); } return flag;} DBconn.java: public static ResultSet selectSql(String sql){ try { PreparedStatement ps; conn = getConn(); ps = conn.prepareStatement(sql); rs = ps.executeQuery(sql); } catch (SQLException e) { System.out.println("sql数据库查询异常"); e.printStackTrace(); } return rs; }这两段代码是为了实现 登录功能,但登录后空指针异常com.dao.UserDaoImpl.login(UserDaoImpl.java:31),31行为while(rs.next()){,优化这两部分代码,使登录功能正常进行
时间: 2023-11-27 18:54:54 浏览: 178
这段代码存在两个问题:
1. 在DBconn.java中,PreparedStatement执行查询语句时,应该使用ps.executeQuery()方法而不是ps.executeQuery(sql)方法。
2. 在UserDaoImpl.java中,如果查询结果集为空,rs.next()方法将返回false,但是rs对象仍然不是null,因此在rs对象为null时应该加上判断。
下面是优化后的代码:
UserDaoImpl.java:
```
public boolean login(String username, String password) {
boolean flag = false;
try {
DBconn.init();
ResultSet rs = DBconn.selectSql("select * from usr where username='" + username + "' and password='" + password + "'");
if (rs != null) {
while (rs.next()) {
if (rs.getString("username").equals(username) && rs.getString("password").equals(password)) {
flag = true;
}
}
rs.close();
}
DBconn.closeConn();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
```
DBconn.java:
```
public static ResultSet selectSql(String sql) {
try {
PreparedStatement ps;
conn = getConn();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
} catch (SQLException e) {
System.out.println("sql数据库查询异常");
e.printStackTrace();
}
return rs;
}
```
阅读全文