我需要在java中通过GPA搜索学生,并按照附图中的要求使用jbdc连接到数据库。
这些是我在数据库中的表:
CREATE TABLE Students (
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(20) NOT NULL,
id VARCHAR(9) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE Classes (
name VARCHAR(50) NOT NULL,
credits INT NOT NULL,
PRIMARY KEY (name)
);
CREATE TABLE IsTaking (
sid VARCHAR(9) NOT NULL,
name VARCHAR(50) NOT NULL,
FOREIGN KEY (sid) REFERENCES Students(id),
FOREIGN KEY (name) REFERENCES Classes(name)
);
CREATE TABLE HasTaken (
sid VARCHAR(9) NOT NULL,
name VARCHAR(50) NOT NULL,
grade CHAR(1) NOT NULL,
FOREIGN KEY (sid) REFERENCES Students(id),
FOREIGN KEY (name) REFERENCES Classes(name)
);
这是我写的java代码:
public static void searchByGPAGreaterThan(Connection conn, Scanner input) throws SQLException {
// Construct the SQL query to select the ID, first name, and last name of all students
// who have taken at least one course and whose GPA is greater than or equal to the threshold.
System.out.print("Enter GPA threshold: ");
double threshold = input.nextDouble();
String query = "SELECT Students.first_name, Students.last_name, Students.id, Classes.credits FROM Students, Classes " +
"WHERE id IN (SELECT sid FROM HasTaken " + "GROUP BY sid HAVING SUM(CASE grade " +
"WHEN 'A' THEN 4 " +
"WHEN 'B' THEN 3 " +
"WHEN 'C' THEN 2 " +
"WHEN 'D' THEN 1 " +
"ELSE 0 END * credits) / SUM(credits) >= ?)";
try {
// Create a prepared statement for the query and set the threshold parameter.
PreparedStatement ps = conn.prepareStatement(query);
ps.setDouble(1, threshold);
// Execute the query and get the result set.
ResultSet rs = ps.executeQuery();
// Print out the results.
while (rs.next()) {
int id = rs.getInt("id");
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
System.out.printf("%d: %s %s\n", id, firstName, lastName);
}
} catch (SQLException e) {
// If there is an error executing the query, print the stack trace.
e.printStackTrace();
}
}
此代码输出所有学生,而不是具有指定 gpa 阈值的特定学生。我不知道如何正确计算学生的 gpa,以便输出只打印适当的学生。
我必须用 100 名学生的数据填充数据库,因此我将为一名学生提供样本数据以供参考:
INSERT INTO Classes (name, credits) VALUES
('Calculus I', 4),
('Introduction to Biology', 3),
('World History', 3);
INSERT INTO Students (first_name, last_name, id) VALUES
('Amabelle', 'Jimmes', '10000');
INSERT INTO IsTaking (sid, name) VALUES
(10000, 'Introduction to Biology'),
(10000, 'Calculus I'),
(10000, 'World History');
INSERT INTO HasTaken (sid, name, grade) VALUES
(10000, 'Introduction to Biology', 'A'),
(10000, 'Calculus I', 'B'),
(10000, 'World History', 'C');
我会更改查询,以便它将原始数据(每个学生)返回给 java 类,然后进行必要的计算
select s.*, group_concat(case ht.grade when 'A' then 4 when 'B' then 3 when 'C' then 2 when 'D' then 1 end) grade from Students s
join HasTaken ht on ht.sid = s.id
join Classes c on c.name = ht.name
group by s.id
;
会产生
first_name last_name id grade
Amabelle Jimmes 10000 4,3,2