如何从MySQL中检测空ResultSet? [英] How to detect empty ResultSet from MySQL?
本文介绍了如何从MySQL中检测空ResultSet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果没有可能的结果,如何检测从MySQL发送的空结果集。
How can I detect the empty result set sending from MySQL if there is no possible result.
推荐答案
检查是否< a href =http://download.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#next%28%29 =noreferrer> ResultSet# next()
返回true。例如
Just check if ResultSet#next()
returns true. E.g.
public boolean exist(String username, String password) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean exist = false;
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT id FROM user WHERE username = ? AND password = MD5(?)");
statement.setString(1, username);
statement.setString(2, password);
resultSet = statement.executeQuery();
exist = resultSet.next();
} finally {
close(resultSet, statement, connection);
}
return exist;
}
您可以使用如下
if (userDAO.exist(username, password)) {
// Proceed with login?
} else {
// Show error?
}
或者,您也可以让它返回fullworhy 用户
或 null
如果没有。例如,
Alternatively, you could also let it return a fullworhy User
or null
if there's none. E.g.
public User find(String username, String password) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
User user = null;
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT id, username, email, dateOfBirth FROM user WHERE username = ? AND password = MD5(?)");
statement.setString(1, username);
statement.setString(2, password);
resultSet = statement.executeQuery();
if (resultSet.next()) {
user = new User(
resultSet.getLong("id"),
resultSet.getString("username"),
resultSet.getString("email"),
resultSet.getDate("dateOfBirth"));
}
} finally {
close(resultSet, statement, connection);
}
return user;
}
User user = userDAO.find(username, password);
if (user != null) {
// Proceed with login?
} else {
// Show error?
}
这篇关于如何从MySQL中检测空ResultSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文