javaweb中实现增删改查的功能的代码
时间: 2023-03-20 12:01:31 浏览: 158
【JavaScript源代码】jQuery实现增删改查.docx
JavaWeb中实现增删改查功能的代码需要依赖于数据库,下面给出一个简单的示例,包含一个学生信息的实体类`Student`和一个学生信息的DAO类`StudentDAO`,用于操作数据库。这里以MySQL为例,使用JDBC连接数据库。
**1. Student类**
```java
public class Student {
private int id;
private String name;
private int age;
private String gender;
private String major;
public Student(int id, String name, int age, String gender, String major) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
this.major = major;
}
//getter and setter methods
}
```
**2. StudentDAO类**
```java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class StudentDAO {
private Connection conn;
public StudentDAO() {
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
String user = "root";
String password = "password";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
//添加学生信息
public boolean addStudent(Student student) {
String sql = "insert into student(name, age, gender, major) values(?,?,?,?)";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, student.getName());
ps.setInt(2, student.getAge());
ps.setString(3, student.getGender());
ps.setString(4, student.getMajor());
int result = ps.executeUpdate();
if(result > 0) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
//删除学生信息
public boolean deleteStudent(int id) {
String sql = "delete from student where id=?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
int result = ps.executeUpdate();
if(result > 0) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
//修改学生信息
public boolean updateStudent(Student student) {
String sql = "update student set name=?, age=?, gender=?, major=? where id=?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, student.getName());
ps.setInt(2, student.getAge());
ps.setString(3, student.getGender());
ps.setString(4, student.getMajor());
ps.setInt(5, student.getId());
int result = ps.executeUpdate();
if(result > 0) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
//查询所有学生信息
public List<Student> getAllStudents() {
String sql = "select * from student";
List<Student> list = new ArrayList<>();
try {
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String gender = rs.getString("gender");
String major = rs.getString("
阅读全文