我想通過查詢數據庫來創建UserInfo對象構造函數,並且我一直收到UserInfo thisUserInfo = new UserInfo()
部分的cannot find symbol
錯誤。我試圖採取ResultSet rs
並填寫構造函數爲登錄的用戶創建「會話」。如何通過查詢Java中的數據庫填充對象構造函數
我在這裏做了什麼錯?這裏是我的代碼:
private UserInfo getUserInfo(HttpServletRequest request, HttpServletResponse response) throws SQLException {
String userName = request.getParameter("userName");
String nullString = null;
char nullChar = ' ';
ResultSet rs = null;
stmt = conn.createStatement();
String getInfoSQL = "SELECT * FROM " + studentsTable + " WHERE USERNAME = '" + userName + "'";
rs = stmt.executeQuery(getInfoSQL);
if(rs.next()) {
UserInfo thisUserInfo = new UserInfo(rs.getString(userName), rs.getString(passWord), rs.getString(lastName), rs.getString(firstName), rs.getString(age), rs.getString(sex), rs.getString(email));
rs.close();
stmt.close();
} else {
UserInfo thisUserInfo = new UserInfo(nullString, nullString, nullString, nullString, nullString, nullChar, nullString);
rs.close();
stmt.close();
}
return thisUserInfo;
}
這裏是我的UserInfo類:
public class UserInfo {
private final String userName;
private final String passWord;
private final String lastName;
private final String firstName;
private final String age;
private final char sex;
private final String email;
public UserInfo(String userName, String passWord, String lastName, String firstName, String age, char sex, String email) {
this.userName = userName;
this.passWord = passWord;
this.lastName = lastName;
this.firstName = firstName;
this.age = age;
this.sex = sex;
this.email = email;
}
public String getUserName() {
return this.userName;
}
public String getPassWord() {
return this.passWord;
}
public String getLastName() {
return this.lastName;
}
public String getFirstName() {
return this.firstName;
}
public String getAge() {
return this.age;
}
public char getSex() {
return this.sex;
}
public String getEmail() {
return this.email;
}
}
謝謝,MadProgrammer。那麼我應該在哪裏定義'userName','passWord'等等?在'getUserInfo()'方法中? – dinky
對不起,我的不好,不斷被拖離電腦。你用來從結果集中提取結果的變量,即'rs.getString(userName)'沒有在任何地方定義(我可以看到),這只是讓我擔心一點;) – MadProgrammer
我看到了...所以我剛剛改變了構造函數參數,這樣我只需要這樣的第n個數據:'UserInfo thisUserInfo = new UserInfo(rs.getString(0),rs.getString(1),rs.getString(2),rs.getString(3 ),rs.getString(4),rs.getString(5).atChar(0),rs.getString(6))''。這會工作得很好嗎? – dinky