gpt4 book ai didi

java - 当我只能访问对象的一个​​字段时,如何返回该对象?

转载 作者:行者123 更新时间:2023-12-02 02:56:28 25 4
gpt4 key购买 nike

抱歉,如果这没有意义,我想不出更好的表达方式。希望我的代码能更好地说明我的问题。

所以在这个方法中我想返回一个Myuser对象。一个 Myuser 对象大约有 8 个字符串字段,其中之一是 userId。

正如你所看到的,当调用这个方法时,会传入一个字符串。如果这个字符串与Myuser对象中的userId字段具有相同的值,那么我希望它返回完整的Myuser对象。否则返回 null。

public Myuser getRecord(String userId) {
Connection cnnct = null;
PreparedStatement pStmnt = null;
Myuser myusr = null;
boolean result = false;

try {
cnnct = getConnection();
String preQueryStatement = "SELECT * FROM MYUSER WHERE USERID = ?";
pStmnt = cnnct.prepareStatement(preQueryStatement);

pStmnt.setString(1, userId);

ResultSet rslt = pStmnt.executeQuery();

result = rslt.next();

if (result) {
//return myusr in its entirety
}

} catch (SQLException ex) {
while (ex != null) {
ex.printStackTrace();
ex = ex.getNextException();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (pStmnt != null) {
try {
pStmnt.close();
} catch (SQLException e) {
}
}
if (cnnct != null) {
try {
cnnct.close();
} catch (SQLException sqlEx) {
}
}
}

return myusr;
}

编辑:我想我也会发布 Myuser 类。

public class Myuser {

private String userid;
private String name;
private String password;
private String email;
private String phone;
private String address;
private String secQn;
private String secAns;

public Myuser(String userid, String name, String password, String email, String phone, String address, String secQn, String secAns) {
this.userid = userid;
this.name = name;
this.password = password;
this.email = email;
this.phone = phone;
this.address = address;
this.secQn = secQn;
this.secAns = secAns;
}

public String getUserid() {
return userid;
}

public void setUserid(String userid) {
this.userid = userid;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getSecQn() {
return secQn;
}

public void setSecQn(String secQn) {
this.secQn = secQn;
}

public String getSecAns() {
return secAns;
}

public void setSecAns(String secAns) {
this.secAns = secAns;
}
}

最佳答案

您可以轻松使用result.getXXX(field_name):

if (rslt.next()) {
myusr = new Myuser(result.getString("userid"), result.getString("name"),
result.getString("password"), result.getString("phone"),
...);
}

注意if(result)之前不需要使用result = rslt.next();,必须直接使用

if (rslt.next()) {
...
}

关于java - 当我只能访问对象的一个​​字段时,如何返回该对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42986433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com