是否为空,但执行以下 *** 作始终会 出错 :
resultSet = statement.executeQuery(sql);string = resultSet.getString(1); // Epic fail. The cursor isn't set yet.
这不是错误。这是记录的行为。每个不错的JDBC教程都提到了它。您需要先使用设置ResultSet的游标,
next()然后才能访问任何数据。
如果您实际上对所谓的唯一行是否 存在 感兴趣,则只需检查的结果
next()。例如在一个虚构
UserDAO类中:
public boolean exist(String username, String password) throws SQLException { boolean exist = false; try ( Connection connection = database.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECt id FROM user WHERe username = ? AND password = MD5(?)"); ) { statement.setString(1, username); statement.setString(2, password); try (ResultSet resultSet = statement.executeQuery()) { exist = resultSet.next(); } } return exist;}
如果你真的希望只有 零 或 一个 行,那么就这样做:
public User find(String username, String password) throws SQLException { User user = null; try ( Connection connection = database.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECt id, username, email, birthdate FROM user WHERe username = ? AND password = MD5(?)"); ) { statement.setString(1, username); statement.setString(2, password); try (resultSet = statement.executeQuery()) { if (resultSet.next()) { user = new User( resultSet.getLong("id"), resultSet.getString("username"), resultSet.getString("email"), resultSet.getDate("birthdate")); } } } return user;}
然后只需在业务/域对象中相应地处理它,例如
User user = userDAO.find(username, password);if (user != null) { // Login?}else { // Show error?}
如果你真的希望只有 零 或 许多 行,那么就这样做:
public List<User> list() throws SQLException { List<User> users = new ArrayList<User>(); try ( Connection connection = database.getConnection(); PreparedStatement statement = connection.prepareStatement("SELECt id, username, email, birthdate FROM user"); ResultSet resultSet = statement.executeQuery(); ) { while (resultSet.next()) { users.add(new User( resultSet.getLong("id"), resultSet.getString("username"), resultSet.getString("email"), resultSet.getDate("birthdate"))); } } return users;}
然后只需在业务/域对象中相应地处理它,例如
List<User> users = userDAO.list();if (!users.isEmpty()) { int count = users.size(); // ...}else { // Help, no users?}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)