用mvc模式使用PreparedStatement完成带条件的查询并用列表存放展示代码
时间: 2024-03-02 07:49:01 浏览: 54
武夷学院-JSP实验七:JSP数据库操作 (2).docx
好的,下面是使用MVC模式、PreparedStatement完成带条件的查询并使用列表存放的Java代码示例:
Student.java:
```java
public class Student {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// 省略getter和setter方法
@Override
public String toString() {
return "id: " + id + ", name: " + name + ", age: " + age;
}
}
```
StudentDAO.java:
```java
public class StudentDAO {
private Connection conn;
public StudentDAO() {
// 初始化数据库连接
conn = DBUtil.getConnection();
}
// 根据年龄查询学生列表
public List<Student> queryByAge(int age) throws SQLException {
List<Student> students = new ArrayList<>();
String sql = "SELECT * FROM student WHERE age >= ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, age);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int ageInDB = rs.getInt("age");
Student student = new Student(id, name, ageInDB);
students.add(student);
}
rs.close();
pstmt.close();
return students;
}
// 关闭数据库连接
public void close() throws SQLException {
conn.close();
}
}
```
StudentController.java:
```java
public class StudentController {
private StudentDAO studentDAO;
public StudentController() {
studentDAO = new StudentDAO();
}
// 根据年龄查询学生列表,并返回结果给界面
public List<Student> queryByAge(int age) throws SQLException {
return studentDAO.queryByAge(age);
}
// 关闭数据库连接
public void close() throws SQLException {
studentDAO.close();
}
}
```
StudentView.java:
```java
public class StudentView {
private StudentController studentController;
public StudentView(StudentController studentController) {
this.studentController = studentController;
}
// 显示学生列表
public void showStudents(List<Student> students) {
for (Student student : students) {
System.out.println(student);
}
}
}
```
Main.java:
```java
public class Main {
public static void main(String[] args) {
try {
// 创建Controller和View
StudentController studentController = new StudentController();
StudentView studentView = new StudentView(studentController);
// 查询学生列表,并将结果显示到界面上
int age = 18;
List<Student> students = studentController.queryByAge(age);
studentView.showStudents(students);
// 关闭数据库连接
studentController.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
上面的代码中,首先定义了Student类,表示学生的信息。然后定义了StudentDAO类,用于与数据库交互进行数据访问操作。StudentController类作为控制器,负责处理界面的请求并调用相应的DAO方法进行数据访问。StudentView类用于显示学生列表到界面上。最后,在Main类中创建Controller和View,并完成查询和显示学生列表的操作。
使用MVC模式可以将程序的各个部分解耦,方便进行维护和扩展。在上面的代码中,如果需要更改数据库连接方式或更改查询条件,只需要修改相应的DAO方法即可,而不会影响到其他部分的代码。
阅读全文