有一个students表,一个courses表,还有一个连接二者的sc表,给出根据cid得到List<Student>的代码
时间: 2024-02-11 21:08:35 浏览: 64
创建student、course、sc表代码.sql
假设students表的结构如下:
| id | name | age | gender |
|----|------|-----|--------|
| 1 | Tom | 18 | M |
| 2 | Jack | 19 | M |
| 3 | Lily | 20 | F |
courses表的结构如下:
| id | name |
|----|----------|
| 1 | English |
| 2 | Math |
| 3 | Chemistry|
sc表的结构如下:
| id | sid | cid |
|----|-----|-----|
| 1 | 1 | 2 |
| 2 | 2 | 1 |
| 3 | 3 | 2 |
| 4 | 1 | 3 |
则可以使用以下代码根据cid得到List<Student>:
```java
public List<Student> getStudentsByCid(int cid) {
List<Student> students = new ArrayList<>();
String sql = "SELECT s.id, s.name, s.age, s.gender " +
"FROM students s " +
"JOIN sc ON s.id = sc.sid " +
"WHERE sc.cid = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, cid);
try (ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String gender = rs.getString("gender");
Student student = new Student(id, name, age, gender);
students.add(student);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return students;
}
```
其中,conn是数据库连接,Student是一个类,表示学生信息。
阅读全文