public Users getUserByName(String name) {
List<Users> userList = new ArrayList<>();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtil.getConn();
String sql = "select * from users where name=?";
ps = conn.prepareStatement(sql);
ps.setString(1, name);
rs = ps.executeQuery();
// 遍历结果集
while (rs.next()) {
// 封装Users
Users users = new Users();
users.setId(rs.getInt("id"));
users.setName(rs.getString("name"));
users.setNickName(rs.getString("nickName"));
users.setPwd(rs.getString("pwd"));
users.setGender(rs.getString("gender"));
users.setBirthday(rs.getDate("birthday"));
users.setHobby(rs.getString("hobby"));
users.setTel(rs.getString("tel"));
users.setEmail(rs.getString("email"));
users.setGrade(rs.getInt("grade"));
users.setDescription(rs.getString("description"));
// 加入list
userList.add(users);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
JdbcUtil.release(rs, conn, ps);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (userList != null && userList.size() > 0) {
return userList.get(0);
} else {
return null;
}
}
为判断userList不为空,使用了两个条件userList != null 和 userList.size() > 0
其中,userList != null 是判断List容器不为空,
userList.size() > 0 是判断容器的内容不为空(可用!userList.isEmpty() 代替)。
这两个判断条件都是必须的,并且顺序也是一定的。即判断容器不为空在先。
本文详细解析了一段Java代码,该代码通过连接数据库并执行SQL查询来获取指定用户名的用户信息。文章深入介绍了如何使用PreparedStatement防止SQL注入,如何遍历结果集并将数据封装到Users对象中,以及如何处理可能发生的SQLException。
1809

被折叠的 条评论
为什么被折叠?



