当前位置:首页 > 行业动态 > 正文

java实现增删查改

Java实现增删查改主要通过操作数据库来实现。首先需要建立数据库连接,然后通过SQL语句来执行增删查改操作。增加一条记录可以使用INSERT语句,删除一条记录可以使用DELETE语句,查询一条记录可以使用SELECT语句,更新一条记录可以使用UPDATE语句。

Java实现增删查改的基本步骤

1、定义数据结构

java实现增删查改  第1张

2、实现增加操作

3、实现删除操作

4、实现查询操作

5、实现更新操作

具体实现

1、定义数据结构

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方法省略
}

2、实现增加操作

import java.util.ArrayList;
import java.util.List;
public class StudentManager {
    private List<Student> students = new ArrayList<>();
    public void addStudent(Student student) {
        students.add(student);
    }
}

3、实现删除操作

public void deleteStudent(int id) {
    for (Student student : students) {
        if (student.getId() == id) {
            students.remove(student);
            break;
        }
    }
}

4、实现查询操作

public Student findStudentById(int id) {
    for (Student student : students) {
        if (student.getId() == id) {
            return student;
        }
    }
    return null;
}

5、实现更新操作

public void updateStudent(Student updatedStudent) {
    for (Student student : students) {
        if (student.getId() == updatedStudent.getId()) {
            student.setName(updatedStudent.getName());
            student.setAge(updatedStudent.getAge());
            break;
        }
    }
}

完整示例代码

import java.util.ArrayList;
import java.util.List;
public class StudentManager {
    private List<Student> students = new ArrayList<>();
    public void addStudent(Student student) {
        students.add(student);
    }
    public void deleteStudent(int id) {
        for (Student student : students) {
            if (student.getId() == id) {
                students.remove(student);
                break;
            }
        }
    }
    public Student findStudentById(int id) {
        for (Student student : students) {
            if (student.getId() == id) {
                return student;
            }
        }
        return null;
    }
    public void updateStudent(Student updatedStudent) {
        for (Student student : students) {
            if (student.getId() == updatedStudent.getId()) {
                student.setName(updatedStudent.getName());
                student.setAge(updatedStudent.getAge());
                break;
            }
        }
    }
}
0