Start(主方法)
package edu.njupt;
import edu.njupt.view.MessageBox;
import edu.njupt.view.StudentManagement;
/**
* @Description: 启动类
* @author: xuHeng
* @date: 2023/2/6 8:40
*/
public class Start {
public static void main(String[] args) throws Exception {
StudentManagement studentManagement = new StudentManagement();
studentManagement.init();
}
}
StudentDao
package edu.njupt.dao;
import com.mysql.cj.jdbc.Driver;
import edu.njupt.domain.Student;
import org.junit.Test;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @Description: 数据库操作
* @author: xuHeng
* @date: 2023/2/6 9:41
*/
public class StudentDao {
//获取数据库
public Connection getConnect() throws Exception {
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
String url = "jdbc:输入你的数据库地址";
String user = "账号";
String password ="密码";
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
//获取所有学生信息
@Test
public List<Student> getAllStudent() throws Exception {
Connection connect = getConnect();
String sql = "select * from student";
PreparedStatement ps = connect.prepareStatement(sql);
ResultSet resultSet = ps.executeQuery();
List<Student> studentList = new ArrayList<>();
while (resultSet.next()) {
Student student = new Student();
student.setSid(resultSet.getString(1));
student.setName(resultSet.getString(2));
student.setAge(Integer.parseInt(resultSet.getString(3)));
student.setBirthday(resultSet.getString(4));
studentList.add(student);
}
connect.close();
return studentList;
}
/**根据条件查询学生*/
public List<Student> queryStudent(Student student1) throws Exception {
System.out.println("查询学生");
Connection connect = getConnect();
StringBuffer sql = new StringBuffer("select * from student where 1=1 ");
if (student1.getSid() != null) {
sql.append("and sid = " + student1.getSid() + " ");
}
if (student1.getAge() != null) {
sql.append("and age = " + student1.getAge() + " ");
}
if (student1.getBirthday() != null) {
sql.append("and birthday = " + student1.getBirthday() + " ");
}
if (student1.getName() != null) {
sql.append("and name = " + student1.getName() + " ");
}
PreparedStatement ps = connect.prepareStatement(String.valueOf(sql));
ResultSet resultSet = ps.executeQuery();
List<Student> studentList = new ArrayList<>();
while (resultSet.next()) {
Student student = new Student();
student.setSid(resultSet.getString(1));
student.setName(resultSet.getString(2));
student.setAge(Integer.parseInt(resultSet.getString(3)));
student.setBirthday(resultSet.getString(4));
studentList.add(student);
}
connect.close();
return studentList;
}
/**sql插入学生信息*/
public void insertStudent(Student student) throws Exception {
Connection connect = getConnect();
String sql = "insert into student(sid,name,age,birthday) values(?,?,?,?)";
PreparedStatement pr