JavaCore-OOP-5-简易的【学生信息管理系统】

Java 专栏收录该内容
130 篇文章 1 订阅

话说:

每天坚持一件事情真不容易。在下前段日子找不到代码写,复杂的写不出来,简单的吧,又觉得太简单,不足以发表,所以隔了这么久才发表这篇…..

今天这篇,也是十分滴基础。实现类似上一篇【图书管理系统】的功能,不过这次不在数组中实现,加入了JDBC,连接了后台,前台通过控制台交互。至于JDBC与前台交互,在笔者前20篇JDBC系列里面总结得很详细了,不在赘述~

目标:
JDBC+控制台 实现学生信息管理系统。核心在于注册功能和JDBC的CURD操作。

开发工具:Eclipse(Oxygen 4.7.0 M7 )

目录


一、效果图
二、实体类
三、Dao层
四、工具类
五、视图类
六、测试类
七、总结


一、效果图

整体框架如下:

这里写图片描述

这里写图片描述

这里写图片描述

这里容易出现InputMismatchException,用try{} catch() {}处理下.

这里写图片描述

注册功能,已经存在给提示(用户名)

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

可以修改全部,也可修改部分字段。

二、实体类

1)创建数据库及表

#1.创建数据库
create database db_stuSys;
use db_stuSys;
#2.创建数据表
create table t_stu(
stu_id int primary key auto_increment comment '学生编号',
stu_name varchar(10) not null comment '学生姓名',
stu_sex char(2) not null comment '性别',
stu_age int unsigned comment '年龄',
stu_grade varchar(5) comment '所属年级',
stu_addr varchar(50) comment '地址',
stu_phone varchar(15) comment '联系方式',
stu_email varchar(15) comment '电子邮箱'
)comment='学生信息表';

#创建用户表
create table t_user(
id int primary key auto_increment comment '用户id',
username varchar(15) comment '用户名',
password varchar(8) comment '密码'
)comment='用户表';

#自封为超级管理员
insert into t_user (username,password) values('meice','321');

后来为便于操作,把stu_sex修改为了varchar()类型.

2)实体类

Student

package com.hmc2.entity;
/**
*
*2017年12月7日
*User:Meice
*下午2:00:55
*/
public class Student {
    private int stu_id;
    private String stu_name;
    private String stu_sex;
    private int stu_age;
    private String stu_grade;
    private String stu_addr;
    private String stu_phone;
    private String stu_email;
    public Student() {}
    public Student(int stu_id, String stu_name, String stu_sex, int stu_age, String stu_grade, String stu_addr,
            String stu_phone, String stu_email) {
        super();
        this.stu_id = stu_id;
        this.stu_name = stu_name;
        this.stu_sex = stu_sex;
        this.stu_age = stu_age;
        this.stu_grade = stu_grade;
        this.stu_addr = stu_addr;
        this.stu_phone = stu_phone;
        this.stu_email = stu_email;
    }

    public Student( String stu_name, String stu_sex, int stu_age, String stu_grade, String stu_addr,
            String stu_phone, String stu_email) {
        this.stu_name = stu_name;
        this.stu_sex = stu_sex;
        this.stu_age = stu_age;
        this.stu_grade = stu_grade;
        this.stu_addr = stu_addr;
        this.stu_phone = stu_phone;
        this.stu_email = stu_email;
    }
    public int getStu_id() {
        return stu_id;
    }
    public void setStu_id(int stu_id) {
        this.stu_id = stu_id;
    }
    public String getStu_name() {
        return stu_name;
    }
    public void setStu_name(String stu_name) {
        this.stu_name = stu_name;
    }
    public String getStu_sex() {
        return stu_sex;
    }
    public void setStu_sex(String stu_sex) {
        this.stu_sex = stu_sex;
    }
    public int getStu_age() {
        return stu_age;
    }
    public void setStu_age(int stu_age) {
        this.stu_age = stu_age;
    }
    public String getStu_grade() {
        return stu_grade;
    }
    public void setStu_grade(String stu_grade) {
        this.stu_grade = stu_grade;
    }
    public String getStu_addr() {
        return stu_addr;
    }
    public void setStu_addr(String stu_addr) {
        this.stu_addr = stu_addr;
    }
    public String getStu_phone() {
        return stu_phone;
    }
    public void setStu_phone(String stu_phone) {
        this.stu_phone = stu_phone;
    }
    public String getStu_email() {
        return stu_email;
    }
    public void setStu_email(String stu_email) {
        this.stu_email = stu_email;
    }
    @Override
    public String toString() {
        return "Student [stu_id=" + stu_id + ", stu_name=" + stu_name + ", stu_sex=" + stu_sex + ", stu_age=" + stu_age
                + ", stu_grade=" + stu_grade + ", stu_addr=" + stu_addr + ", stu_phone=" + stu_phone + ", stu_email="
                + stu_email + "]";
    }




}

User

package com.hmc2.entity;
/**
*
*2017年12月7日
*User:Meice
*下午2:01:03
*/
public class User {
    private int userid;
    private String username;
    private String password;
    public User() {}
    public User(String username,String password) {
        this.username = username;
        this.password = password;
    }
    public User(int userid,String username,String password) {
        this.userid = userid;
        this.username = username;
        this.password = password;
    }
    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    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;
    }
    @Override
    public String toString() {
        return "User [userid=" + userid + ", username=" + username + ", password=" + password + "]";
    }



}

三、Dao层

1) 接口-JdbcDao

package com.hmc2.dao;
/**
*
*2017年12月7日
*User:Meice
*下午2:45:06
*/
import java.util.List;

public interface JdbcDao {
    public int Cud(String sql,Object... params);
    public List<?> list(String sql,Object... params);
}

2)实现类-JdbcDaoImpl

package com.hmc2.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import com.hmc2.entity.Student;
import com.hmc2.entity.User;
import com.hmc2.util.JdbcUtil;
import com.hmc2.util.MatcherUtil;
import com.hmc2.view.ControllerView;

/**
*
*2017年12月7日
*User:Meice
*下午2:49:47
*/
public class JdbcDaoImpl  implements JdbcDao{
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    //实例化验证学生信息类
    MatcherUtil mu = new MatcherUtil();
    //实例化ControllerView类
    ControllerView  cv = new ControllerView();

    /**
     * 1.增删改
     */
    @Override
    public int Cud(String sql, Object... params) {
        int result =0;
        //1.获取连接
        conn = JdbcUtil.getConnection();
        try {
            ps = conn.prepareStatement(sql);
            if(params != null) {
                for(int i=0;i<params.length;i++) {
                    ps.setObject((i+1), params[i]);
                }
            }
            //2.执行语句
            result = ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 2.查
     */
    @Override
    public List<?> list(String sql, Object... params) {
        List<Student> listStu = new ArrayList<Student>();
        conn = JdbcUtil.getConnection();
        try {
            ps = conn.prepareStatement(sql);
            //可以带参,也可以不带参s
            if(params != null) {
                for(int i=0;i<params.length;i++) {
                    ps.setObject((i+1), params[i]);
                }
            }
            rs = ps.executeQuery();
            while(rs.next()) {
                int stu_id = rs.getInt("stu_id");
                String stu_name = rs.getString("stu_name");
                String stu_sex = "男";
                try {
                     stu_sex = rs.getString("stu_sex");
                }catch(NullPointerException e) {
                        stu_sex = "男";
                }

                int stu_age = rs.getInt("stu_age");
                String stu_grade = rs.getString("stu_grade");
                String stu_addr = rs.getString("stu_addr");
                String stu_phone = rs.getString("stu_phone");
                String stu_email = rs.getString("stu_email");
                Student student = new Student(stu_id, stu_name, stu_sex, stu_age, stu_grade, stu_addr, stu_phone, stu_email);
                listStu.add(student);
                //System.out.println(listStu);
            }
        } catch (SQLException e) {

            e.printStackTrace();
        }

        return listStu;
    }


    /**
     * 3.根据CUD结果给出对应信息提示
     * getResultOfCudInfo()
     */
    public void getResultCudInfo(int result,String successInfo,String failInfo) {
        if(result>0) {
            System.out.println(successInfo);
        }else {
            System.out.println(failInfo);
        }
    }


    /**
     * 4.根据用户名判断用户是否存在
     * isUserExist()
     * 带2个参数,灵活性增加:判断注册有效否,只用判断用户名;判断登录,则要用户名、密码一起判断
     */
    public boolean isUserExist(User user,String sql,String existInfo,Object... params) {
        conn= JdbcUtil.getConnection();
        //String sql = "select * from t_user where username = ?";
        try {
            ps =    conn.prepareStatement(sql);
            if(params!= null) {
                for(int i=0;i<params.length;i++) {
                    ps.setObject((i+1), params[i]);
                }
            }
            //ps.setString(1, user.getUsername());
            rs =    ps.executeQuery();
            if(rs.next()) {
                System.out.println(existInfo);
                return true;
            }else {
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 5.定义注册
     * studentRegister()
     * 
     */
    public void studentRegister(User user) {
        //User user2 =  cv.getUser("亲,输入【注册用户名】:", "输入【注册密码】:", "");
        //判断用户是否已经存在
        String sql1 = "select * from t_user where username = ?";
        Object[] parmas = {user.getUsername()};
        if(isUserExist(user, sql1,"用户【已注册】,请重新选择操作:", parmas)) {
            //方法内已经处理
        }else {
            //执行添加用户方法
            String sql2  = "insert into t_user (username,password) values (?,?)";
            Object[] params2 = {user.getUsername(),user.getPassword()};
            int result =    Cud(sql2, params2);
            getResultCudInfo(result, "恭喜你!注册成功! *.* ", "遗憾,注册失败...");
            System.out.println("请牢记已注册用户名:"+user.getUsername()+"  密码:"+user.getPassword());

        }
    }


    /**
     * 6.查看学生列表
     * studentList()
     */
    public void studentList() {
        String sql = "select * from t_stu";
        List<Student> list =(List<Student>)list(sql, null);
        System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++所有学生信息++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        //这里不要list==null来判断,对象存在当然不为null
        if(list.size()==0) {
            System.out.println("暂无学员信息!请新增后再查看~ ");
        }else {
            System.out.println("* id\t|姓名\t|性别\t|年龄\t|年级\t|家庭地址\t\t\t|电话\t\t\t|邮箱\t\t*");
            for(Student stu:list) {
                System.out.println("* "+stu.getStu_id()+"\t|"+stu.getStu_name()+"\t|"+stu.getStu_sex()+"\t|"+stu.getStu_age()+"\t|"+stu.getStu_grade()+"\t|"+stu.getStu_addr()+"\t\t\t|"+stu.getStu_phone()+"\t\t|"+stu.getStu_email()+" *");
            }
        }
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
    }

    /**
     * 7.新增学生
     * addStudent()
     */

    public void addStudent(Student student) {
        //Student student = mu.getStudent();
        String sql3 = "insert into t_stu (stu_name,stu_sex,stu_age,stu_grade,stu_addr,stu_phone,stu_email)"
                + "values (?,?,?,?,?,?,?)";
        Object[] params3 = {student.getStu_name(),student.getStu_sex(),student.getStu_age(),student.getStu_grade(),student.getStu_addr(),student.getStu_phone(),student.getStu_email()};
        int result =    Cud(sql3, params3);
        getResultCudInfo(result, "恭喜亲,【新增】成功!", "遗憾,【新增】失败");
    }

    /**
     * 8.删除学生
     * delStudent()
     */
    public void delStudent(int stu_id) {
        String sql6 = "delete from t_stu where stu_id = ? ";
        //int stu_id = cv.getStuId("请输入要【删除】学生的Id:");
        Object[] params6 = {stu_id};

        //打印删除信息

        //判断Id存在,存在在删除,不存在给精确提示;这里之所以不封装,是因为要输出删除信息,不然封装会更啰嗦
        String sql = "select * from t_stu where stu_id = ?";
        Object[] params = {stu_id};
        List<Student> list2 =(List<Student>)list(sql, params);
        if(list2.size()==0) {
            System.out.println("该ID不存在...");
        }else {
            System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++【待删除】学生信息++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            System.out.println("* id\t|姓名\t|性别\t|年龄\t|年级\t|家庭地址\t\t\t\t|电话\t\t\t|邮箱\t\t*");
            for(Student stu:list2) {
                System.out.println("* "+stu.getStu_id()+"\t|"+stu.getStu_name()+"\t|"+stu.getStu_sex()+"\t|"+stu.getStu_age()+"\t|"+stu.getStu_grade()+"\t|"+stu.getStu_addr()+"\t\t\t|"+stu.getStu_phone()+"\t\t|"+stu.getStu_email()+"\t*");
            }
            System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

            //删除前要确认删除信息
            int result2 = 0;
            if(cv.isContinue("确认删除(y/n)?")) {
                result2 = Cud(sql6, params6);
                getResultCudInfo(result2, "恭喜亲,【删除】成功!", "遗憾,【删除】失败");
            }else {
                System.out.println("未执行【删除】操作~");
            }
        }

    }



    /**
     * 9.修改1——根据学生Id修改全部信息
     * updateStuInfoById()
     * 假设Id是存在的
     */

    public void updateStuInfoById(int stu_id) {
        //用户Id存在前提下才有修改的意义
        if(isStudentExistById(stu_id)) {
            String sql = "update t_stu set stu_name =?,stu_sex=?,stu_age=?,stu_grade=?,stu_addr=?,stu_phone=?,stu_email=? ";
            Student student =   mu.getStudent();
            Object[] params = {student.getStu_name(),student.getStu_sex(),student.getStu_age(),student.getStu_grade(),student.getStu_addr(),student.getStu_phone(),student.getStu_email()};
            //打印修改 后的信息,确认是否修改
            System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++【待修改】学生信息++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            System.out.println("* id\t|姓名\t|性别\t|年龄\t|年级\t|家庭地址\t\t\t\t|电话\t\t\t|邮箱\t\t*");
                System.out.println("* "+stu_id+"\t|"+student.getStu_name()+"\t|"+student.getStu_sex()+"\t|"+student.getStu_age()+"\t|"+student.getStu_grade()+"\t|"+student.getStu_addr()+"\t\t\t|"+student.getStu_phone()+"\t\t|"+student.getStu_email()+"\t*");
            System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

            if(cv.isContinue("请核对以上【待修改】信息,确认修改(y/n)?")) {
                int result =    Cud(sql, params);
                getResultCudInfo(result, "恭喜,【修改成功!】", "遗憾,【修改】失败~");
            }else {
                System.out.println("未执行【修改】操作");
            }
        }else {
            System.out.println("该ID不存在奥~");
        }


    }

    /**
     * 10.修改2——根据学生Id修改部分属性
     * updateLittleStuInfoById()
     */

    public int updateLittleStuInfoById(int stu_id) {
        int result = 0;
        if(isStudentExistById(stu_id)) {
            System.out.println("亲,请输入要修改的属性:");
            String stuProperty = new Scanner(System.in).next();
            System.out.println("亲,请输入要修改后的值:");
            String stuVal = new Scanner(System.in).next();
            String sql = "update t_stu set "+ stuProperty+" = ? where stu_id = ?";
            Object[] params = {stuVal,stu_id};

            //输出修改后的信息
            System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++【待修改】学生信息++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            System.out.println("* id\t|"+stuProperty+"\t*");
                System.out.println("* "+stu_id+"\t|"+stuVal+"\t*");
            System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

            //询问是否执行修改

            if(cv.isContinue("请核对以上【待修改】信息,确认修改(y/n)?")) {
            result =    Cud(sql, params);
            }else {
                System.out.println("属性未修改~");
            }
        }else {
            System.out.println("该用户Id不存在~");
        }
        return result;
    }

    /**
     * 11.根据stu_id返回一个对象
     * getStudentById
     */
    public Student getStudentById(int stu_id) {
        String sql = "select * from t_stu where id = ?";
        Object[] params = {stu_id};
        List<Student> list =(List<Student>) list(sql, params);
        return list.get(0);
    }


    /**
     * 12.根据Id判断学生是否存在
     * isStudentExistById()
     */
    public boolean isStudentExistById(int stu_id) {
        String sql = "select * from t_stu where stu_id = ?";
        Object[] params = {stu_id};
        List<Student> list =(List<Student>) list(sql, params);
        if(list.size()==0) {
            return false;
        }else{
            return true;
        }
    }

}

这里面还是有很大优化空间,比如User的查和Student的查通过泛型是可以合并的,如果再加入对用户的后台管理,那很多代码都可以复用。

四、工具类

1)把获取JDBC连接封装成对象,便于调用
2)JDBC连接优化为加载静态资源
3)获取一个Student,验证各种条件

1)把获取JDBC连接封装成对象,便于调用

JdbcUtil

package com.hmc2.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
*
*2017年12月7日
*User:Meice
*下午2:20:47
*/
public class JdbcUtil {
    private JdbcUtil() {}
    static Connection connection = null;

    /**
     * 1.定义静态语句块,加载驱动
     */
    static {
        try {
            Class.forName(JdbcProperUtil.getJdbcVal().getProperty("driver"));
            /*connection = DriverManager.getConnection(JdbcProperUtil.getJdbcVal().getProperty("url"),
                    JdbcProperUtil.getJdbcVal().getProperty("root"), JdbcProperUtil.getJdbcVal().getProperty("password"));*/
            connection = DriverManager.getConnection(JdbcProperUtil.getJdbcVal().getProperty("url"),JdbcProperUtil.getJdbcVal().getProperty("username"),JdbcProperUtil.getJdbcVal().getProperty("password"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 2.定义获取驱动方法getConnection() 
     */
    public static Connection getConnection() {
        return connection;
    }

    /**
     * 3.定义关闭资源的方法
     * closeJdbc()
     */
    public void closeJdbc(ResultSet rs,PreparedStatement ps,Connection conn) {
        try {
            if(rs != null) rs.close();
            if(ps != null) ps.close();
            if(conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } 
    }


}

2)JDBC连接优化为加载静态资源

JdbcProperUtil

package com.hmc2.util;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Properties;

import org.junit.Test;

/**
*
*2017年12月7日
*User:Meice
*下午3:01:34
*/
public class JdbcProperUtil {
    /**
     * 这个类用来获取JDBC静态资源
     */
    @Test
    public static Properties getJdbcVal() {
        Properties properties = new Properties();
        Reader reader;
        try {
            reader = new FileReader("db.properties");
            properties.load(reader);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }

public static void main(String[] args) {
    //Properties properties = getJdbcVal();
    //System.out.println(properties.getProperty("root"));
}

}

3)获取一个Student,验证各种条件

MatcherUtil

package com.hmc2.util;
import java.util.InputMismatchException;
import java.util.Scanner;
import org.junit.Test;
import com.hmc2.entity.Student;

/**
*
*2017年12月7日
*User:Meice
*下午4:54:35
*/
public class MatcherUtil {
    Scanner sc = new Scanner(System.in);

    /**
     * 这里面最核心的是正则校验(这里暂且不用正则)
     * 其次就是重复调用方法,思路很好
     * @return
     */
    @Test
    public  Student getStudent() {
        try {
            stu_name = setStu_name();
            stu_sex =   setStu_sex();
            stu_age = setStu_age();
            stu_grade = setStu_grade();
            stu_addr = setStu_addr();
            stu_phone = setStu_phone();
            stu_email = setStu_email();
        }catch(InputMismatchException e) {
            System.out.println("输入有误,请重新输入:");
            this.getStudent();
        }
        Student student = new Student(stu_name, stu_sex, stu_age, stu_grade, stu_addr, stu_phone, stu_email);
        //System.out.println(student);
        return student;
    }

    public static void main(String[] args) {
        MatcherUtil mu = new MatcherUtil();
        mu.getStudent();
    }
    private int stu_id;
    private String stu_name;
    private String stu_sex;
    private int stu_age;
    private String stu_grade;
    private String stu_addr;
    private String stu_phone;
    private String stu_email;
    public MatcherUtil() {}
    public MatcherUtil(int stu_id, String stu_name, String stu_sex, int stu_age, String stu_grade, String stu_addr,
            String stu_phone, String stu_email) {
        super();
        this.stu_id = stu_id;
        this.stu_name = stu_name;
        this.stu_sex = stu_sex;
        this.stu_age = stu_age;
        this.stu_grade = stu_grade;
        this.stu_addr = stu_addr;
        this.stu_phone = stu_phone;
        this.stu_email = stu_email;
    }

    public MatcherUtil( String stu_name, String stu_sex, int stu_age, String stu_grade, String stu_addr,
            String stu_phone, String stu_email) {
        this.stu_name = stu_name;
        this.stu_sex = stu_sex;
        this.stu_age = stu_age;
        this.stu_grade = stu_grade;
        this.stu_addr = stu_addr;
        this.stu_phone = stu_phone;
        this.stu_email = stu_email;
    }
    public int getStu_id() {
        return stu_id;
    }
    public void setStu_id(int stu_id) {
        this.stu_id = stu_id;
    }
    public String getStu_name() {
        return stu_name;
    }
    public String setStu_name() {
        System.out.println("姓名:");
        stu_name = sc.next();
        return stu_name;
    }
    public String getStu_sex() {
        return stu_sex;
    }

    public String setStu_sex() {
        System.out.println("性别:");
        stu_sex = sc.next();
        if("男".equals(stu_sex)||"女".equals(stu_sex)) {

        }else {
            System.out.println("性别输入有误,请输入【男】或【女】");
            this.setStu_sex();
        }
        return stu_sex;
    }
    public int getStu_age() {
        return stu_age;
    }

    public int  setStu_age() {
        System.out.println("年龄:");
        stu_age = sc.nextInt();
        if(stu_age>=1 && stu_age<120) {
        }else {
            System.out.println("年龄有误,请重新输入:");
            this.setStu_age();
        }
        return stu_age;
    }


    public String getStu_grade() {
        return stu_grade;
    }
    public String setStu_grade() {
        System.out.println("年级【初级、中级、高级】:");
        stu_grade = sc.next();
        if("初级".equals(stu_grade)||"中级".equals(stu_grade)||"高级".equals(stu_grade)) {

        }else {
            System.out.println("输入有误,请选择以下三个选项之一【初级、中级、高级】");
            this.setStu_grade();
        }
        return stu_grade;
    }
    public String getStu_addr() {
        return stu_addr;
    }
    public String setStu_addr() {
        System.out.println("家庭住址:");
        stu_addr = sc.next();
        return stu_addr;
    }
    public String getStu_phone() {
        return stu_phone;
    }
    public String setStu_phone() {
        System.out.println("手机号码:");
        stu_phone = sc.next();
        if(stu_phone.length() ==11) {

        }else {
            System.out.println("手机号码输入有误,请输入11位手机号码:");
            this.setStu_phone();
        }
        return stu_phone;
    }
    public String getStu_email() {
        return stu_email;
    }
    public String setStu_email() {
        System.out.println("邮箱:");
        stu_email = sc.next();
        if(stu_email.contains("@")&&stu_email.contains(".com")) {

        }else {
            System.out.println("邮箱有误!必须包含@和.com奥~");
            this.setStu_email();
        }
        return stu_email;
    }








}

这里对手机号码、邮箱验证都不够精确,通过正则是最为精确的验证方式。
以下为正则方式验证,非本人所写。

package com.yijian.utils;

import java.util.Scanner;
import java.util.regex.Pattern;

public class Matches {
    Scanner input = new Scanner(System.in);
    static String id = null;
    static String gender = null;
    static String age = null;
    static String grade = null;
    static String phone = null;
    static String email = null;

    /**
     * 匹配id
     * 
     * @return
     */
    public String matchesId() {
        id = input.next();
        if (Pattern.matches("^[0-9]{1,}$", id)) {

        } else {
            System.out.println("输入错误,只能输入数字:");
            this.matchesId();
        }
        return id;
    }

    /**
     * 匹配性别
     * 
     * @return
     */
    public String matchesGender() {
        gender = input.next();
        if (!(gender.equals("男") || gender.equals("女"))) {
            System.out.println("性别只能是男或者女:");
            this.matchesGender();
        }
        return gender;
    }

    /**
     * 匹配年龄
     * 
     * @return
     */
    public int matchesAge() {
        age = input.next();
        if (!Pattern.matches("^[0-9]{1,}$", age)) {
            System.out.println("以上输入不合法,只能输入1-120之内的数字:");
            this.matchesAge();
        } else if (Integer.valueOf(age) < 1 || Integer.valueOf(age) > 120) {
            System.out.println("以上输入不合法,只能输入1-120之内的数字:");
            this.matchesAge();
        }
        return Integer.parseInt(age);
    }

    /**
     * 匹配年级
     * 
     * @return
     */
    public String matchesGrade() {
        grade = input.next();
        if (!(grade.equals("初级") || grade.equals("中级") || grade.equals("高级"))) {
            System.out.println("无此年级设置,年级只能输入初级、中级或高级,请重新输入:");
            this.matchesGrade();
        }
        return grade;
    }

    /**
     * 匹配手机号
     * 
     * @return
     */
    public String matchesPhone() {
        phone = input.next();
        if (!Pattern.matches("^[0-9]{11}$", phone)) {
            System.out.println("输入有误,电话号码只能是11位数字,请重新输入:");
            this.matchesPhone();
        }
        return phone;
    }

    /**
     * 匹配email
     * 
     * @return
     */
    public String matchesEmail() {
        email = input.next();
        if (!Pattern.matches("^[0-9a-zA-Z]+@[0-9a-zA-Z]+.[0-9a-zA-Z]+$", email)) {
            System.out.println("邮箱格式有误,请输入正确的电子邮箱(包含@和.com)");
            this.matchesEmail();
        }
        return email;
    }
}

五、视图类

控制台在这里扮演UI的角色,委屈UI了。
ControllerView

package com.hmc2.view;

import java.util.InputMismatchException;
import java.util.Scanner;

import com.hmc2.entity.User;

/**
*
*2017年12月7日
*User:Meice
*下午1:42:15
*/
public class ControllerView {
    /**
     * 1.定义登陆界面方法
     * welcomeLogin()
     */
    public void welcomeLogin() {
        System.out.println("***********************欢迎【进入】学生管理系统*******************************");
        System.out.println("\t1.登录\t\t2.注册\t\t3.退出");
        System.out.println("************************************************************************");
    }

    /**
     * 2.定义接收用户名和参数的方法
     * getUser()
     */
    public User getUser(String startUserInfo, String StartPwdInfo,String endInfo) {
        System.out.println(startUserInfo);
        String username = new Scanner(System.in).next();
        System.out.println(StartPwdInfo);
        String password = new Scanner(System.in).next();
        User user = new User(username, password);
        return user;
    }




    /**
     * 3.判断是否继续方法
     * isContinue()
     */
    public boolean isContinue(String startInfo) {
        System.out.println(startInfo);
        String choice = new Scanner(System.in).next();
        if("y".equals(choice)|| "Y".equals(choice)) {
            return true;
        }else if("n".equals(choice)|| "N".equals(choice)) {
            return false;
        }else {
            System.out.println("输入有误,请重新输入【y/Y表示继续,n/N表示终止】:");
            if(this.isContinue(startInfo)) {
                return true;
            }else {
                return false;
            }
        }

    }

    /**
     * 4.获取用户选择的选项
     * getChooseNumber()
     */

    public int getChooseNumber() {
        System.out.println("亲,输入【序号】选择你要的操作:");
        try {
            int chooseNumber = new Scanner(System.in).nextInt();
            return chooseNumber;
        }catch(InputMismatchException e) {
                System.out.println("输入有误奥,请重新输入【整数】序号:");
                try {
                    int chooseNumber2 = new Scanner(System.in).nextInt();
                    return chooseNumber2;
                }catch(InputMismatchException e2) {
                    return  this.getChooseNumber();
                }
        }
    }


    /**
     * 5.定义登录成功后的界面
     * welcomeEnter()
     */
    public void welcomeEnter() {
        System.out.println("---------------------亲,按照对应【序号】选择操作---------------------------");
        System.out.println("1.查看学生信息\t2.新增学生\t\t3.删除学员\t\t4.修改学生信息\t5.退出登录");
        System.out.println("---------------------------------------------------------------------");
    }


    /**
     * 6.定义获取学生id的方法
     * getStuId()
     */
    public int getStuId(String info ) {
        int stu_id =0;
        try {
            System.out.println(info);
            stu_id = new Scanner(System.in).nextInt();
        }catch(InputMismatchException e) {
            this.getStuId("输入id有误,请重新输入:");
        }
        return stu_id;
    }

    /**
     * 7.定义修改学生信息欢迎界面
     * welcomeUpdate()
     */
    public void welcomeUpdate() {
        System.out.println(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
        System.out.println("*  1.根据ID修改学生全部信息\t2.根据ID修改学生部分信息\t3.返回上级目录\t4.系统退出\t*");
        System.out.println(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");

    }
}


封装起来可以使后面的测试类异常简洁清晰。

六、测试类

TestStudentManagementSystem

package com.hmc2.test;
import java.util.List;
import com.hmc2.dao.JdbcDaoImpl;
import com.hmc2.entity.Student;
import com.hmc2.entity.User;
import com.hmc2.util.MatcherUtil;
import com.hmc2.view.ControllerView;

/**
*
*2017年12月7日
*User:Meice
*下午1:41:53
*/
public class TestStudentManagementSystem {
    //界面层对象
    static ControllerView cv = new ControllerView();
    //dao层对象
    static JdbcDaoImpl jdi = new JdbcDaoImpl();
    //实例化MatcherUtil类;用于获取一个Student对象
    static MatcherUtil mu = new MatcherUtil();

    public static void main(String[] args) throws InterruptedException {
        boolean flag1 = true;
        do {
            cv.welcomeLogin();
            switch(cv.getChooseNumber()) {
            case 1:
                //TODO Login
                User user = cv.getUser("亲,输入【用户名】:", "输入【密码】:", "");
                String sql = "select * from t_user where username = ? and password = ?";
                Object[] params = {user.getUsername(),user.getPassword()};

                //用户名及密码都正确,提示登录成功
                if(jdi.isUserExist(user, sql,"欢迎【"+user.getUsername()+"】!登录成功! *.* ", params)) {
                    boolean flag2 = true;
                    System.out.println("正在登录......");
                    Thread.sleep(1000);
                    //已处理
                    do {
                        cv.welcomeEnter();
                        switch(cv.getChooseNumber()) {
                        case 1:
                            //TODO 查看学生信息
                            jdi.studentList();
                            System.out.println("系统自动返回上层目录......");
                            Thread.sleep(1000);
                            break;
                        case 2:
                            //TODO 新增学生信息
                            jdi.addStudent(mu.getStudent());
                            System.out.println("系统自动返回上层目录......");
                            Thread.sleep(1000);
                            break;
                        case 3:
                            //TODO 删除学生信息
                            jdi.studentList();
                            jdi.delStudent(cv.getStuId("请输入要【删除】学生的Id:"));
                            System.out.println("系统自动返回上层目录......");
                            Thread.sleep(2000);
                            break;
                        case 4:
                            //TODO 修改学生信息
                            boolean flag3 = true;
                            do {
                                cv.welcomeUpdate();
                                switch(cv.getChooseNumber()) {
                                case 1:
                                    //TODO 根据Id修改全部信息
                                    jdi.studentList();
                                    jdi.updateStuInfoById(cv.getStuId("请输入【待修改学生Id】:"));
                                    flag3 = false;
                                    System.out.println("程序正在返回上一级目录......");
                                    Thread.sleep(1000);

                                    break;
                                case 2:
                                    //TODO 根据Id修改部分信息
                                    jdi.studentList();
                                    int result =    jdi.updateLittleStuInfoById(cv.getStuId("请输入【待修改学生Id】:"));
                                    jdi.getResultCudInfo(result, "恭喜!【属性修改】成功!", "遗憾,属性修改失败~");
                                    flag3 = false;
                                    System.out.println("程序正在返回上一级目录......");
                                    Thread.sleep(1000);
                                    break;
                                case 3:
                                    //TODO  返回上一级
                                    flag3 = false;
                                    System.out.println("程序正在返回上一级目录......");
                                    Thread.sleep(1000);
                                    break;
                                case 4:
                                    //TODO 系统退出
                                    flag3 = false;
                                    flag2 = false;
                                    break;
                                default:
                                    //TODO Others
                                    System.out.println("输入【序号】有误,程序自动返回上一级.....");
                                    Thread.sleep(5000);
                                    break;
                                }

                            }while(flag3);
                            break;
                        case 5:
                            //TODO 退出登录
                            System.out.println("您已退出,请重新进入学生管理系统~ *.* ");
                            flag2 = false;
                            break;
                        default:
                            //TODO Others
                            System.out.println("序号不存在,请重新输入~ *.* ");
                            break;                      
                        }
                    }while(flag2);
                }else {
                    System.out.println("用户不存在,请重新选择操作:");
                }
                break;
            case 2:
                //TODO Register
                jdi.studentRegister(cv.getUser("亲,输入【注册用户名】:", "输入【注册密码】:", ""));
                System.out.println("正在进入系统......");
                Thread.sleep(3000);
                break;
            case 3:
                //TODO Exit
                System.out.println("再会! *.* ~");
                flag1 = false;
                break;
            default :
                //TODO Others
                System.out.println("该序号不存在,请重新选择!");
                break;
            }

        }while(flag1);
    }
}

这是在下精简后的精简,测试类精简到这一步,算是可以了。然而,Dao的实现类还有不少优化空间。

七、总结


1.功能实现没有太多问题,细节多,特殊情况要考虑周全,比如根据Id删除和修改的前提是ID都要存在,否则操作没意义;

2.如果用户输入错误,需要让用户反复输入直至正确为止,或者限定试错次数类似的场景,采用方法自我调用;

3.java.sql.SQLException: Incorrect string value: ‘\xAC\xED\x00\x05sr…’ for column ‘stu_sex’ at row 1出现类似的编码问题,要么修改属性,要么尝试如下解决:

url=jdbc:mysql://localhost:3306/db_stusys?useUnicode=true&characterEncoding=utf8

4.根据Id判断对象是否存在可以通过查所有的方法来判断,就是结果集List的size()>0表示存在;否则不存在,这样比较简洁;或者重写一个方法判断ResultSet.next(),这个代码就冗余啦;

5.框架因为底层封装好,可以直接传递整个对象,这里故意不用框架,所以传参和接收参数就比较痛苦;

6.PreparedStatement对象执行语句,参数化SQL语句有讲究。

String sql = "update t_stu set stu_sex = ? where stu_id = ?";

这里set 后面的属性不能为变量呢?
可以的,不能直接这样

 String sql = "update t_stu set ? = ? where stu_id = ?";

这样是不行的。字段名和表名一样,不可以用?表示。怎么搞定,传变量。

类似这样处理:

String stuProperty = new Scanner(System.in).next();
String sql = "update t_stu set "+ stuProperty+" = ? where stu_id = ?";

7.还是老话——温故而知新,不惧路途遥远,进一寸有一寸的欢喜。


好了,晚安!下次再会!~

  • 0
    点赞
  • 0
    评论
  • 3
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:技术黑板 设计师:CSDN官方博客 返回首页

打赏作者

那起舞的日子

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值