2 回答

TA貢獻1872條經驗 獲得超4個贊
您分享的兩個片段都是錯誤的。
在第一個片段中,您執行了一個查詢(順便說一句,由于字符串連接,該查詢容易受到 SQL 注入的攻擊),但忽略其結果并僅檢查作為參數傳遞的對象。
在第二個片段中,您再次執行查詢,但忽略結果,從數據庫中獲取所有用戶,并檢查他們是否存在。
相反,您需要根據傳遞的參數進行查詢,并檢查查詢是否返回了任何結果:
@Override
public ApiResponseDto getlogin(UserDto usersLogin) {
try {
// Assumption: The connection is pooled, and doesn't require closing.
Connection con = getConnection();
try (Preparestament ps = con.preparestament("select * from tableregister where username = ? and password = ?") {
ps.setString(1, usersLogin.getUsername());
ps.setString(2, userLoging.getPassword());
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return new ApiResponseDto("Success", "Login Success");
} else {
ApiResponseDto obj = new ApiResponseDto("Error", "Error Login");
obj.setErrorCode(1);
return obj;
}
}
}
} catch (Exception e) {
e.printStackTrace(); // Or log the error somehow
return new ApiResponseDto("Error", "Error: " + e.toString());
}
}
PS:
請注意,在您的兩個代碼段中,您都沒有正確關閉 JDBC 對象,從而導致泄漏。這可以使用 try-with-resource 語法相對巧妙地完成。

TA貢獻1828條經驗 獲得超13個贊
您需要檢查結果集。您可以這樣做。
ResutSet rs = st.executeQuery....
if(rs.next()) {
String username = r.getUserName();
...
}
添加回答
舉報