我班上有这个方法,
public static AccountHolder getAccountHolder(String username, String password) {
try {
String verifyQuery = "SELECT COUNT(username) FROM accountholder WHERE username=? AND password=?)";
connection = getConnection();
ptmt = connection.prepareStatement(verifyQuery);
ptmt.setString(4, username);
ptmt.setString(5, password);
ResultSet verified = ptmt.executeQuery();
if (verified.next()) {
// Only one Result
if (verified.getInt(1) == 1) {
connection.close();
return 1;
} else {
connection.close();
return null;
}
}
} catch (Exception ex) {
}
}
我知道我应该返回AccountHolder类型的对象,它是一个类。 AccountHolder类代码如下:
public class AccountHolder {
private String firstname;
private String lastname;
private String username;
private String password;
private String address;
private String phonenumber;
// get & set methods();
}
我应该返回匹配的用户名&使用该方法从数据库中获取密码我怎样才能做到这一点?
答案 0 :(得分:0)
您需要将作为答案获得的ResultSet
元素转换为AccountHolder
的对象,并将其返回而不是行return 1;
。
答案 1 :(得分:0)
尝试更改代码
PreparedStatement stmt = conn.prepareStatement(
"SELECT USERNAME FROM accountholder
WHERE USERNAME = ? AND PASSWORD = ?");
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
// valid credentials
} else {
// invalid credentials
}
答案 2 :(得分:0)
您可以采用一种方法,如果找到针对输入用户名和密码的匹配记录,则返回具体的AccountHolder对象,否则为null。
尝试这样的方法,根据您的架构更改列名:
public static AccountHolder getAccountHolder(String username,String password){
AccountHolder accountHolder = null;
try {
String verifyQuery = "SELECT * FROM accountholder WHERE username=? AND password=?)";
connection = getConnection();
ptmt = connection.prepareStatement(verifyQuery);
ptmt.setString(1, username);
ptmt.setString(2, password);
ResultSet verified = ptmt.executeQuery();
if (verified.next()) {
accountHolder = new AccountHolder();
accountHolder.setFirstName(rs.getString("FIRSTNAME"));
accountHolder.setLastName(rs.getString("LASTNAME"));
accountHolder.setUsername(rs.getString("USERNAME"));
accountHolder.setPassword(rs.getString("PASSWORD"));
accountHolder.setAddress(rs.getString("ADDRESS"));
accountHolder.setPhoneNumber(rs.getString("PHONENUMBER"));
}
} catch (Exception ex) {
} finally {
connection.close();
}
return accountHolder ;
}
答案 3 :(得分:0)
Change that prepared statement query like this
pm.setString(1,username);
pm.setString(2,password);
and
assign the setters like this
accountholder.setUserName(verified.getString(1));
accountholder.setpassword(verified.getString(2));
get those values in array or any collection for retrieval.