欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

学生管理系统(JAVA-MYSQL-控制台输出)

程序员文章站 2024-01-26 15:08:52
...

学生管理系统(JAVA-MYSQL-控制台输出)

一、运行效果
学生管理系统(JAVA-MYSQL-控制台输出)
学生管理系统(JAVA-MYSQL-控制台输出)

二、代码:

2.1 AdminDao

package com.sdsc.stumanger.dao;

import com.sdsc.stumanger.entity.Student;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

public class AdminDao extends BaseDao {
    /**
     * 验证管理员的用户名和密码
     *
     * @param username 用户名
     * @param password 密码
     * @return true or false
     */

    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    public boolean checkAdmin(String username, String password) throws SQLException {
        conn = super.getConnection();
        boolean flag = false;

        try {
            //构造SQL语句
            String sql = "SELECT id FROM admin where username = ? and password = ?";

            //创建执行对象
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);

            //执行查询,得到结果集
            rs = ps.executeQuery();

            //对结果集进行遍历
            while (rs.next()) {
                flag = true;
            }
        } catch (SQLException e) {
            //异常处理
            e.printStackTrace();
        } finally {
            //释放资源
            super.release(null, ps, conn);
        }

        return flag;
    }

}

2.2 BaseDao

package com.sdsc.stumanger.dao;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    private static String driver = "";
    private static String url = "";
    private static String user = "";
    private static String password = "";

    static {
        Properties p = new Properties();
        try {
            p.load(BaseDao.class.getClassLoader().getResourceAsStream("db.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = p.getProperty("driver");
        url = p.getProperty("url");
        user = p.getProperty("username");
        password = p.getProperty("password");

        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();

        }
    }

    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            System.out.println("数据库连接错误!请检查配置项目!");
            e.printStackTrace();
        }
        return null;
    }
    //释放的时候要从小到大释放
    //Connection -> Statement --> Resultset

    public static void release(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

2.3 StudentDao

package com.sdsc.stumanger.dao;

import com.sdsc.stumanger.entity.Student;
import com.sun.org.glassfish.external.statistics.annotations.Reset;
import sun.management.snmp.jvminstr.JvmThreadInstanceEntryImpl;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;

public class StudentDao extends BaseDao {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    // 增加学生信息的方法
    public int addStudent(Student stu) {
        // 获得驱动程序
        conn = super.getConnection();

        int num = 0;
        try {
            //创建SQL语句
            String sql = "INSERT INTO student (stuId, stuName, stuBirthday, stuPhone, stuAddress) VALUES (?, ?, ?, ?, ?)";
            //创建执行对象
            ps = conn.prepareStatement(sql);
            //根据情况完善SQL语句
            ps.setInt(1, stu.getStuId());
            ps.setString(2, stu.getStuName());
            ps.setDate(3, Date.valueOf(stu.getStuBirthday()));
            ps.setString(4, stu.getStuPhone());
            ps.setString(5, stu.getStuAddress());

            //执行更新操作
            num = ps.executeUpdate();

        } catch (SQLException e) {
            //异常处理
            e.printStackTrace();
        } finally {
            //释放资源
            super.release(null, ps, conn);
        }
        return num;
    }

    // 查看所有学生信息的方法
    public ArrayList<Student> getAllStudent() {
        conn = super.getConnection();
        //创建学生集合
        ArrayList<Student> list = new ArrayList<>();
        // 创建学生类对象
        Student stu;

        try {
            //构造SQL语句
            String sql = "SELECT * FROM student";

            //创建执行对象
            ps = conn.prepareStatement(sql);

            //执行查询,得到结果集
            rs = ps.executeQuery();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

            //对结果集进行遍历
            while (rs.next()) {
                //实例化学生对象
                stu = new Student();

                //利用set方法对学生对象进行赋值
                stu.setStuId(rs.getInt("stuId"));
                stu.setStuName(rs.getString("stuName"));
                stu.setStuBirthday(formatter.format(rs.getDate("stuBirthday")));
                stu.setStuPhone(rs.getString("stuPhone"));
                stu.setStuAddress(rs.getString("stuAddress"));

                //将学生对象添加到集合中
                list.add(stu);
            }
        } catch (SQLException e) {
            //异常处理
            e.printStackTrace();
        } finally {
            //释放资源
            super.release(null, ps, conn);
        }

        //返回学生集合
        return list;
    }

    // 根据学号查找学生信息
    public Student searchByStuId(int stuId) {
        conn = super.getConnection();
        // 创建学生类对象
        Student stu = null;

        try {
            //构造SQL语句
            String sql = "SELECT * FROM student where stuId = ?";

            //创建执行对象
            ps = conn.prepareStatement(sql);
            ps.setInt(1, stuId);

            //执行查询,得到结果集
            rs = ps.executeQuery();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

            //对结果集进行遍历
            while (rs.next()) {
                stu = new Student();
                //利用set方法对学生对象进行赋值
                stu.setStuId(rs.getInt("stuId"));
                stu.setStuName(rs.getString("stuName"));
                stu.setStuBirthday(formatter.format(rs.getDate("stuBirthday")));
                stu.setStuPhone(rs.getString("stuPhone"));
                stu.setStuAddress(rs.getString("stuAddress"));

                break;
            }
        } catch (SQLException e) {
            //异常处理
            e.printStackTrace();
        } finally {
            //释放资源
            super.release(null, ps, conn);
        }

        //返回学生集合
        return stu;
    }

    // 更新学生信息的方法
    public int updateStudent(Student stu, int stuId) {
        conn = super.getConnection();
        // 创建学生类对象
        int num = 0;

        try {
            //构造SQL语句
            String sql = "update student set stuName = ?, stuBirthday = ?, stuPhone = ?, stuAddress = ? where stuId = ?";

            //创建执行对象
            ps = conn.prepareStatement(sql);
            ps.setString(1, stu.getStuName());
            ps.setString(2, stu.getStuBirthday());
            ps.setString(3, stu.getStuPhone());
            ps.setString(4, stu.getStuAddress());
            ps.setInt(5, stuId);

            //执行查询,得到结果集
            num = ps.executeUpdate();
        } catch (SQLException e) {
            //异常处理
            System.out.println("更新失败!");
            e.printStackTrace();
        } finally {
            //释放资源
            super.release(null, ps, conn);
        }

        return num;
    }

    // 根据学号删除学生信息
    public int deleteByStuId(int stuId) {
        conn = super.getConnection();
        int num = 0;

        try {
            //构造SQL语句
            String sql = "delete from student where stuId = ?";

            //创建执行对象
            ps = conn.prepareStatement(sql);
            ps.setInt(1, stuId);
            //执行删除
            num = ps.executeUpdate();
        } catch (SQLException e) {
            //异常处理
            System.out.println("删除失败!");
            e.printStackTrace();
        } finally {
            //释放资源
            super.release(null, ps, conn);
        }

        return num;
    }

}

2.4 Admin

package com.sdsc.stumanger.entity;

public class Admin {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Admin() {
    }

    public Admin(String username, String password) {

        this.username = username;
        this.password = password;
    }

    @Override
    public String toString() {
        return "Admin{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

2.5 Student

package com.sdsc.stumanger.entity;

public class Student {
    private int stuId;
    private String stuName;
    private String stuBirthday;
    private String stuPhone;
    private String stuAddress;

    public int getStuId() {
        return stuId;
    }

    public void setStuId(int stuId) {
        this.stuId = stuId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getStuBirthday() {
        return stuBirthday;
    }

    public void setStuBirthday(String stuBirthday) {
        this.stuBirthday = stuBirthday;
    }

    public String getStuPhone() {
        return stuPhone;
    }

    public void setStuPhone(String stuPhone) {
        this.stuPhone = stuPhone;
    }

    public String getStuAddress() {
        return stuAddress;
    }

    public void setStuAddress(String stuAddress) {
        this.stuAddress = stuAddress;
    }

    public Student() {
    }

    public Student(int stuId, String stuName, String stuBirthday, String stuPhone, String stuAddress) {
        this.stuId = stuId;
        this.stuName = stuName;
        this.stuBirthday = stuBirthday;
        this.stuPhone = stuPhone;
        this.stuAddress = stuAddress;
    }

    @Override
    public String toString() {
        String stuStr = "学号:" + stuId + "\n" + "姓名:" + stuName + "\n" + "出生日期:" + stuBirthday +
                "\n" + "电话:" + stuPhone + "\n" + "住址:" + stuAddress;

        return stuStr;
    }
}

2.6 Tools

package com.sdsc.stumanger.tools;

import com.sdsc.stumanger.dao.StudentDao;
import com.sdsc.stumanger.entity.Student;

import java.util.ArrayList;

public class Tools {

    // 打印学生信息
    public static void print(ArrayList<Student> list) {
        for (Student st : list){
            System.out.println(st.toString());
            System.out.println();
        }
    }

    public void println(String s) {
        System.out.println(s);
    }
}

2.7 StuManagerCUI

package com.sdsc.stumanger.view;

import com.sdsc.stumanger.dao.AdminDao;
import com.sdsc.stumanger.dao.StudentDao;
import com.sdsc.stumanger.entity.Student;
import com.sdsc.stumanger.tools.Tools;
import com.sun.javafx.image.BytePixelSetter;

import javax.sound.midi.Soundbank;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Scanner;

public class StuManagerCUI {

    Scanner input = new Scanner(System.in);
    StudentDao sd = new StudentDao();
    Tools t = new Tools();

    // 登录验证的方法
    public boolean loginCUI() throws SQLException, InterruptedException {
        AdminDao ad = new AdminDao();
        boolean checkResult = false;
        int num = 0;

        while (num < 3) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输出管理员账号:");
            String username = sc.nextLine();
            System.out.println("请输入管理员密码:");
            String password = sc.nextLine();

            //用户名、密码验证3次仍不正确,退出系统
            checkResult = ad.checkAdmin(username, password);

            if (checkResult) {
                System.out.print("输入正确!正在进入系统,请稍后");
                Thread.sleep(1000);
                System.out.print("..");
                Thread.sleep(1000);
                System.out.print("..");
                Thread.sleep(1000);
                System.out.print("..");
                break;
            } else {
                num += 1;
                System.out.println("账号或密码错误,请重新输入!您还有[" + (3 - num) + "]次机会");
                System.out.println();

                if (num == 3) {
                    System.out.println("管理员身份验证失败!");
                    System.out.print("正在关闭系统");
                    Thread.sleep(1000);
                    System.out.print("..");
                    Thread.sleep(1000);
                    System.out.print("..");
                    Thread.sleep(1000);
                    System.out.print("..");
                }
            }
        }

        return checkResult;
    }

    // 进入主界面的方法
    public void mainCUI() {
        String tag = "";
        int choice = 0;
        while (!tag.equals("5")) {
            System.out.println();
            System.out.println("*****************************************");
            System.out.println("\t学生管理系统主界面");
            System.out.println("1.添加学生");
            System.out.println("2.查看所有学生");
            System.out.println("3.删除学生");
            System.out.println("4.修改学生信息");
            System.out.println("5.退出系统");
            System.out.print("请选择(1-5):");
            try {
                tag = input.next();
                choice = Integer.parseInt(tag);
                switch (choice) {
                    case 1:
                        // 增加学生信息
                        addStudentCUI();
                        break;
                    case 2:
                        // 查看所有学生信息
                        selectStudentCUI();
                        break;
                    case 3:
                        // 删除学生信息
                        deleteStudentCUI();
                        break;
                    case 4:
                        // 更新学生信息
                        updateStudentCUI();
                        break;
                    case 5:
                        // 退出系统
                        t.println("退出系统,谢谢使用");
                        System.out.print("正在关闭系统");
                        Thread.sleep(1000);
                        System.out.print("..");
                        Thread.sleep(1000);
                        System.out.print("..");
                        Thread.sleep(1000);
                        System.out.print("..");
                        System.exit(0);
                    default:
                        System.out.println("输入错误,请重新输入!");

                }
            } catch (Exception e) {
                System.out.println("输入错误,请重新输入!");
            }
        }
    }

    // 增加学生信息
    public void addStudentCUI() {
        // 显示增加学生信息界面
        System.out.println("********************************");
        System.out.println("开始添加学生");
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入学生学号:");
        int stuId = Integer.parseInt(sc.nextLine());
        boolean checkid = checkStuByID(stuId);
        if (!checkid) {
            System.out.print("请输入学生姓名:");
            String stuName = sc.nextLine();
            System.out.print("请输入学生生日(格式1988-01-01):");
            String stuBirthday = sc.nextLine();
            System.out.print("请输入学生电话:");
            String stuPhone = sc.nextLine();
            System.out.print("请输入学生住址:");
            String stuAddress = sc.nextLine();

            Student stu = new Student(stuId, stuName, stuBirthday, stuPhone, stuAddress);
            int num = sd.addStudent(stu);
            if (num == 1) {
                System.out.println("添加成功!");
            } else {
                System.out.println("添加失败!");
            }
        } else {
            System.out.println("该学生已存在,请重新输入");
        }
    }

    // 查看学生全部信息
    public void selectStudentCUI() {
        // 输出学生信息列表
        System.out.println("********************************");
        System.out.println("全部学生信息为:");
        ArrayList<Student> stu = sd.getAllStudent();
        t.print(stu);
    }

    // 更新学生信息
    public void updateStudentCUI() {
        System.out.println("********************************");
        System.out.println("开始更新学生信息");
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要更新的学生id:");
        int stuId = Integer.parseInt(sc.nextLine());
        boolean checkid = checkStuByID(stuId);
        if (checkid) {
            System.out.print("请输入学生姓名:");
            String stuName = sc.nextLine();
            System.out.print("请输入学生生日(格式1988-01-01):");
            String stuBirthday = sc.nextLine();
            System.out.print("请输入学生电话:");
            String stuPhone = sc.nextLine();
            System.out.print("请输入学生住址:");
            String stuAddress = sc.nextLine();
            Student stu = new Student(stuId, stuName, stuBirthday, stuPhone, stuAddress);

            int num = sd.updateStudent(stu, stuId);
            if (num == 1) {
                System.out.println("更新成功!");
            } else {
                System.out.println("更新失败!");
            }
        } else {
            System.out.println("该学生不存在,请重新输入");
        }
    }

    // 删除学生信息
    public void deleteStudentCUI() {
        // 显示删除学生信息界面
        System.out.println("********************************");
        System.out.println("开始删除学生");
        System.out.print("请输入要删除的学生id:");
        Scanner sc = new Scanner(System.in);
        int stuId = Integer.parseInt(sc.nextLine());
        boolean checkid = checkStuByID(stuId);
        if (checkid) {
            int num = sd.deleteByStuId(stuId);
            if (num == 1) {
                System.out.println("删除成功!");
            } else {
                System.out.println("删除失败!");
            }
        } else {
            System.out.println("该学生不存在,请重新输入");
        }
    }

    //检查当前学生是否存在
    public boolean checkStuByID(int ID) {
        // 通过学号检测学生信息是否存在
        Student stu = sd.searchByStuId(ID);
        if (stu != null) {
            return true;
        } else {
            return false;
        }
    }


}

2.8 Main

package com.sdsc.stumanger;
import com.sdsc.stumanger.view.StuManagerCUI;

import java.sql.SQLException;

public class Main {

    public static void main(String[] args) throws SQLException, InterruptedException {
        StuManagerCUI smc = new StuManagerCUI();
        boolean login = smc.loginCUI();
        if (login) {
            smc.mainCUI();
        }
    }
}


2.9 db.properties

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8
username = root
password = 123456