【发布时间】:2020-11-04 22:58:33
【问题描述】:
您好,我有一个问题在这里无法解决:
为 getPeople () 方法编写代码,使其构造并返回一个 从数据库中检索到的 Person 类型对象的 ArrayList。
java.sql.Connection 类型的对象已被初始化。 SQL 数据库包含一个包含 3 列的人员表:id(自动递增整数) , first_name (varchar), last_name (varchar)。
使用 Connection 对象,从表中检索所有记录,并为每个 记录使用相应的字段来创建Person类型的对象。添加每个 Person 类型对象因此在您的 ArrayList 中创建。 返回结果列表。
这是必须完成的代码:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql. *;
import java.util.ArrayList;
import java.util. *;
public class ExerciseImpl {
public void runExercise (String [] argv) throws Exception {
}
public ArrayList <Person> getPeople () throws Exception {
Connection conn = this.getCandidateConnection ();
/ * ---------- DO NOT CHANGE THE CODE ABOVE THIS LINE, IT WILL BE RESET ON RUN ---------- * /
/ **** Enter your code here **** /
/ * ---------- DO NOT CHANGE THE CODE BELOW THIS LINE, IT WILL BE RESET WHEN RUNNING ---------- * /
}
}
class Person {
public int id;
public String firstName;
public String lastName;
Person (int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
}
这是我想出的代码:
public class ExerciseImpl {
public void runExercise (String [] argv) throws Exception {
}
public ArrayList <Person> getPeople () throws Exception {
ResultSet resultSet=null;
try( Connection conn = this.getCandidateConnection();
Statement statement= conn.createStatement();){
String selectSql = "SELECT id, first_name, last_name from people";
resultSet = statement.executeQuery(selectSql);
}catch (SQLException e){
e.printStackTrace();
}
}
/ * ---------- DO NOT CHANGE THE CODE BELOW THIS LINE, IT WILL BE RESET WHEN RUNNING ---------- * /
}
}
class Person {
public int id;
public String firstName;
public String lastName;
Person (int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
}
老实说,我完成不了多少(我只是创建了没有正文的 getCandidateConnection () 方法) 因为我不知道怎么做 完成它,其余的,我不知道如何在 java 程序中查询数据库。 基本上,我很难解决这个问题。
你能帮帮我吗?
【问题讨论】:
-
您更改了“请勿更改此行下方的代码,它将在运行时重置”行下方的代码?这是为了上课还是为了工作?你希望下一个任务做什么?