Java实训第三次,第四次实训

1.创建数据库访问接口

在net.lyq.student包中创建如下图所示的包–bao,用来存放数据库的对应接口。
在这里插入图片描述

2.创建第一个对应接口–学校数据访问接口

创建bean目录下College类所对应的接口CollegeDao.
在这里插入图片描述
详细代码如下:
在这里插入图片描述

3.创建第二个对应接口–状态数据访问接口

创建状态数据访问接口:
在这里插入图片描述
接口详细代码如下:
在这里插入图片描述

4.创建第三个对应接口–学生数据访问接口

在这里插入图片描述
详细代码如下:

在这里插入图片描述

5.创建第四个对应访问接口–用户数据访问接口

在这里插入图片描述
详细代码为:
在这里插入图片描述

6.创建数据访问接口实现类

在dao包中创建子包impl

在这里插入图片描述

7.创建学校数据访问接口实现类

在这里插入图片描述
下面展示一些 内联代码片

package net.lyq.student.dao.impl;

import net.lyq.student.bean.College;
import net.lyq.student.dao.CollegeDao;
import net.lyq.student.dbutil.ConnectionManager;

import java.sql.*;

public class CollegeDaoImpl implements CollegeDao {
    @Override
    public College findById(int id) {
        College college = null;
        //获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        //定义SQL字符
        String strSQL = "select * from t_college where id = ?";
        try {
            PreparedStatement pstmt  = conn.prepareStatement(strSQL);
            pstmt.setInt(1,id);
            ResultSet rs = pstmt.executeQuery();
            if(rs.next()){
                college.setId(rs.getInt("id"));
                college.setName(rs.getString("name"));
                college.setPresident(rs.getString("president"));
                college.setStartTime(rs.getTimestamp("start_time"));
                college.setTelephone(rs.getString("telephone"));
                college.setEmail(rs.getString("email"));
                college.setAddress(rs.getString("address"));
                college.setProfile(rs.getString("profile"));
            }
            //关闭预备语句对象
            pstmt.close();
            //关闭结果集对象
            rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            //关闭连接
            ConnectionManager.closeConnection(conn);
        }
        //返回学校对象
        return college;
    }

    @Override
    public int update(College college) {
        //定义更新记录数
        int count = 0;
        //获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        //定义SQL字符串
        String strSQL = "update t_college set name = ? ,president = ? ,start_time = ? "
                        + "teltphone = ? ,email = ? , adress = ?, profile = ? where id = ?";
        try {
            //设置占位符的值
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            pstmt.setString(1,college.getName());
            pstmt.setString(2,college.getPresident());
            pstmt.setTimestamp(3,new Timestamp( college.getStartTime().getTime()));
            pstmt.setString(4,college.getTelephone());
            pstmt.setString(5,college.getEmail());
            pstmt.setString(6,college.getAddress());
            pstmt.setString(7, college.getProfile());
            pstmt.setInt(8,college.getId());
            //执行SQL,返回更新记录数
            count = pstmt.executeUpdate();
            pstmt.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            ConnectionManager.closeConnection(conn);
        }
        return count;
    }
}

8.单元测试:对CollegeDaoImpl进行单元测试

在这里插入图片描述
下面展示一些 内联代码片

package net.lyq.student.test;

import net.lyq.student.bean.College;
import net.lyq.student.dao.CollegeDao;
import net.lyq.student.dao.impl.CollegeDaoImpl;
import org.junit.Test;

public class TestCollegeDaoImpl {
    @Test
    public void testFindById(){
        //创建学校接口类访问接口对象
        CollegeDao dao = new CollegeDaoImpl();
        //调用学校数据访问对象的查找方法,获取学校对象
        College college = dao.findById(1);
        //输出学校信息
        System.out.println("校名:"+college.getName());
        System.out.println("校长:"+college.getPresident());
        System.out.println("地址:"+college.getAddress());
        System.out.println("邮箱:"+college.getEmail());
        System.out.println("电话:"+college.getTelephone());

    }
    @Test
    public void testUpdate(){
        CollegeDao dao = new CollegeDaoImpl();
        College college = dao.findById(1);
        college.setPresident("王洪礼");
        int count = dao.update(college);
        if (count > 0){
            System.out.println("学校记录更新成功!!!");
            System.out.println("新校长"+dao.findById(1).getPresident());
        }else{
            System.out.println("学校记录更新失败!!");
        }


    }
}

在此代码中包含两个单元测试方法testFindById(),testUpdate(),添加测试注解符@test,如需使用@test注解方法,需要使用JUnit4,讲@test添加进入JUnit4的类路径

由于两种测试方法的第一行代码相同,则可以提取出来,放在两种测试方法的外层。
在每个单元测试之前都要执行的代码,我们可以将代码放在一个方法里面,但是加上一个注解符@Before即可。
在每个单元测试之后都要执行的代码,我们可以将代码放在一个方法里面,但是加上一个注解符@After即可。

9.创建状态数据访问接口实现类

在这里插入图片描述
下面展示一些 内联代码片

package net.lyq.student.dao.impl;
import net.lyq.student.bean.Status;
import net.lyq.student.dao.StatusDao;
import net.lyq.student.dbutil.ConnectionManager;

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



    public class StatusDaoImpl implements StatusDao {
        @Override
        public Status findById(int id) {
            // 声明状态对象
            Status status = null;

            // 1. 获取数据库连接对象
            Connection conn = ConnectionManager.getConnection();
            // 2. 定义SQL字符串
            String strSQL = "SELECT * FROM t_status WHERE id = ?";
            try {
                // 3. 创建预备语句对象
                PreparedStatement pstmt = conn.prepareStatement(strSQL);
                // 4. 设置占位符的值
                pstmt.setInt(1, id);
                // 5. 执行SQL查询,返回结果集
                ResultSet rs = pstmt.executeQuery();
                // 6. 判断结果集是否有记录
                if (rs.next()) {
                    // 实例化状态
                    status = new Status();
                    // 利用当前记录字段值去设置状态对象的属性
                    status.setId(rs.getInt("id"));
                    status.setCollege(rs.getString("college"));
                    status.setVersion(rs.getString("version"));
                    status.setAuthor(rs.getString("author"));
                    status.setTelephone(rs.getString("telephone"));
                    status.setAddress(rs.getString("address"));
                    status.setEmail(rs.getString("email"));
                }
                // 7. 关闭预备语句对象
                pstmt.close();
                // 8. 关闭结果集对象
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                // 关闭数据库连接
                ConnectionManager.closeConnection(conn);
            }

            // 返回状态对象
            return status;
        }

        @Override
        public int update(Status status) {
            // 定义更新记录数
            int count = 0;

            // 1. 获得数据库连接
            Connection conn = ConnectionManager.getConnection();
            // 2. 定义SQL字符串
            String strSQL = "update t_status set college = ?, version = ?, author = ?,"
                    + " telephone = ?, address = ?, email = ? where id = ?";
            try {
                // 3. 创建预备语句对象
                PreparedStatement pstmt = conn.prepareStatement(strSQL);
                // 4. 设置占位符的值
                pstmt.setString(1, status.getCollege());
                pstmt.setString(2, status.getVersion());
                pstmt.setString(3, status.getAuthor());
                pstmt.setString(4, status.getTelephone());
                pstmt.setString(5, status.getAddress());
                pstmt.setString(6, status.getEmail());
                pstmt.setInt(7, status.getId());
                // 5. 执行更新操作,更新记录
                count = pstmt.executeUpdate();
                // 6. 关闭预备语句对象
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                // 关闭数据库连接
                ConnectionManager.closeConnection(conn);
            }

            // 返回更新记录数
            return count;
        }
    }


====

10.对StatusDaoImpl进行单元测试

在test包下建立测试类
在这里插入图片描述
下面展示一些 内联代码片

package net.lyq.student.test;

import net.lyq.student.bean.Status;
import net.lyq.student.dao.StatusDao;
import net.lyq.student.dao.impl.StatusDaoImpl;
import org.junit.Test;

public class TestStatusDaoImpl {
    StatusDao dao = new StatusDaoImpl();
    @Test
    public void testFindById(){
        Status status = dao.findById(1);
        System.out.println("作者:"+status.getAuthor());
        System.out.println("学校:"+status.getCollege());
        System.out.println("版本:"+status.getVersion());
        System.out.println("地址:"+status.getAddress());
        System.out.println("电话:"+status.getTelephone());
        System.out.println("邮箱:"+status.getEmail());
    }
}

11.编写testUpdate方法

在这里插入图片描述
运行结果:
在这里插入图片描述

12.学生数据访问接口实现类

在这里插入图片描述
下面展示一些 内联代码片

package net.lyq.student.dao.impl;

import net.lyq.student.bean.Student;
import net.lyq.student.dao.StudentDao;
import net.lyq.student.dbutil.ConnectionManager;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class StudentDaoImpl implements StudentDao {
    @Override
    public int insert(Student student) {
        // 定义插入记录数
        int count = 0;

        // 1. 获得数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "insert into t_student (id, name, sex, age, department, class, telephone)"
                + " values (?, ?, ?, ?, ?, ?, ?)";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setString(1, student.getId());
            pstmt.setString(2, student.getName());
            pstmt.setString(3, student.getSex());
            pstmt.setInt(4, student.getAge());
            pstmt.setString(5, student.getDepartment());
            pstmt.setString(6, student.getClazz());
            pstmt.setString(7, student.getTelephone());
            // 5. 执行SQL,返回插入记录数
            count = pstmt.executeUpdate();
            // 6. 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回插入记录数
        return count;
    }

    /**
     * 按学号删除学生记录
     *
     * @param id
     * @return 删除记录数
     */
    @Override
    public int deleteById(String id) {
        // 定义删除记录数
        int count = 0;

        // 1. 获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "delete from t_student where id = ?";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setString(1, id);
            // 5. 执行SQL,返回删除记录数
            count = pstmt.executeUpdate();
            // 6. 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回删除记录数
        return count;
    }

    /**
     * 按班级删除学生记录
     *
     * @param clazz
     * @return 删除记录数
     */
    @Override
    public int deleteByClass(String clazz) {
        // 定义删除记录数
        int count = 0;

        // 1. 获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "delete from t_student where class = ?";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setString(1, clazz);
            // 5. 执行SQL,返回删除记录数
            count = pstmt.executeUpdate();
            // 6. 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回删除记录数
        return count;
    }

    /**
     * 按系部删除学生记录
     *
     * @param department
     * @return 删除记录数
     */
    @Override
    public int deleteByDepartment(String department) {
        // 定义删除记录数
        int count = 0;

        // 1. 获得数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "delete from t_student where department = ?";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setString(1, department);
            // 5. 执行SQL,返回删除记录数
            count = pstmt.executeUpdate();
            // 6. 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回删除记录数
        return count;
    }

    /**
     * 更新学生记录
     *
     * @param student
     * @return 更新记录数
     */
    @Override
    public int update(Student student) {
        // 定义更新记录数
        int count = 0;

        // 1. 获得数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "update t_student set name = ?, sex = ?, age = ?,"
                + " department = ?, class = ?, telephone = ? where id = ?";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setString(1, student.getName());
            pstmt.setString(2, student.getSex());
            pstmt.setInt(3, student.getAge());
            pstmt.setString(4, student.getDepartment());
            pstmt.setString(5, student.getClazz());
            pstmt.setString(6, student.getTelephone());
            pstmt.setString(7, student.getId());
            // 5. 执行SQL,返回更新记录数
            count = pstmt.executeUpdate();
            // 6. 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回更新记录数
        return count;
    }

    /**
     * 按学号查询学生记录
     *
     * @param id
     * @return 学生实体
     */
    @Override
    public Student findById(String id) {
        // 声明学生对象
        Student student = null;

        // 1. 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "select * from t_student where id = ?";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setString(1, id);
            // 5. 执行SQL,返回结果集
            ResultSet rs = pstmt.executeQuery();
            // 6. 判断结果集是否有记录
            if (rs.next()) {
                // 创建学生实体
                student = new Student();
                // 利用当前记录各字段值设置学生实体属性
                student.setId(rs.getString("id"));
                student.setName(rs.getString("name"));
                student.setSex(rs.getString("sex"));
                student.setAge(rs.getInt("age"));
                student.setDepartment(rs.getString("department"));
                student.setClazz(rs.getString("class"));
                student.setTelephone(rs.getString("telephone"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回学生对象
        return student;
    }

    /**
     * 按姓名查询学生记录
     *
     * @param name
     * @return 学生列表
     */
    @Override
    public List<Student> findByName(String name) {
        // 声明学生列表
        List<Student> students = new ArrayList<Student>();

        // 1. 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "select * from t_student where name like ?";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setString(1, name + "%");
            // 5. 执行SQL,返回结果集
            ResultSet rs = pstmt.executeQuery();
            // 6. 遍历结果集
            while (rs.next()) {
                // 创建学生实体
                Student student = new Student();
                // 利用当前记录各字段值设置学生实体属性
                student.setId(rs.getString("id"));
                student.setName(rs.getString("name"));
                student.setSex(rs.getString("sex"));
                student.setAge(rs.getInt("age"));
                student.setDepartment(rs.getString("department"));
                student.setClazz(rs.getString("class"));
                student.setTelephone(rs.getString("telephone"));
                // 将实体添加到学生列表
                students.add(student);
            }
            // 7. 关闭结果集
            rs.close();
            // 8. 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回学生列表
        return students;
    }

    /**
     * 按班级查询学生记录
     *
     * @param clazz
     * @return 学生列表
     */
    @Override
    public List<Student> findByClass(String clazz) {
        // 声明学生列表
        List<Student> students = new ArrayList<Student>();

        // 1. 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "select * from t_student where class like ?";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setString(1, clazz + "%");
            // 5. 执行SQL,返回结果集
            ResultSet rs = pstmt.executeQuery();
            // 6. 遍历结果集
            while (rs.next()) {
                // 创建学生实体
                Student student = new Student();
                // 利用当前记录各字段值设置学生实体属性
                student.setId(rs.getString("id"));
                student.setName(rs.getString("name"));
                student.setSex(rs.getString("sex"));
                student.setAge(rs.getInt("age"));
                student.setDepartment(rs.getString("department"));
                student.setClazz(rs.getString("class"));
                student.setTelephone(rs.getString("telephone"));
                // 将实体添加到学生列表
                students.add(student);
            }
            // 7. 关闭结果集
            rs.close();
            // 8. 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回学生列表
        return students;
    }

    /**
     * 按系部查询学生记录
     *
     * @param department
     * @return 学生列表
     */
    @Override
    public List<Student> findByDepartment(String department) {
        // 声明学生列表
        List<Student> students = new ArrayList<Student>();

        // 1. 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "select * from t_student where department like ?";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setString(1, department + "%");
            // 5. 执行SQL,返回结果集
            ResultSet rs = pstmt.executeQuery();
            // 6. 遍历结果集
            while (rs.next()) {
                // 创建学生实体
                Student student = new Student();
                // 利用当前记录各字段值设置学生实体属性
                student.setId(rs.getString("id"));
                student.setName(rs.getString("name"));
                student.setSex(rs.getString("sex"));
                student.setAge(rs.getInt("age"));
                student.setDepartment(rs.getString("department"));
                student.setClazz(rs.getString("class"));
                student.setTelephone(rs.getString("telephone"));
                // 将实体添加到学生列表
                students.add(student);
            }
            // 7. 关闭结果集
            rs.close();
            // 8. 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回学生列表
        return students;
    }

    /**
     * 查询全部学生记录
     *
     * @return 学生列表
     */
    @Override
    public List<Student> findAll() {
        // 声明学生列表
        List<Student> students = new ArrayList<Student>();

        // 1. 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "select * from t_student";
        try {
            // 3. 创建语句对象
            Statement stmt = conn.createStatement();
            // 4. 执行SQL,返回结果集
            ResultSet rs = stmt.executeQuery(strSQL);
            // 5. 遍历结果集
            while (rs.next()) {
                // 创建学生实体
                Student student = new Student();
                // 利用当前记录各字段值设置学生实体属性
                student.setId(rs.getString("id"));
                student.setName(rs.getString("name"));
                student.setSex(rs.getString("sex"));
                student.setAge(rs.getInt("age"));
                student.setDepartment(rs.getString("department"));
                student.setClazz(rs.getString("class"));
                student.setTelephone(rs.getString("telephone"));
                // 将实体添加到学生列表
                students.add(student);
            }
            // 6. 关闭结果集
            rs.close();
            // 7. 关闭语句对象
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回学生列表
        return students;
    }

    /**
     * 按性别统计学生人数
     *
     * @return 统计结果向量
     */
    @Override
    public Vector findRowsBySex() {
        // 定义行集向量
        Vector rows = new Vector();

        // 1. 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "select sex as '性别', count(*) as '人数'"
                + " from t_student group by sex order by sex desc";
        try {
            // 3. 创建语句对象
            Statement stmt = conn.createStatement();
            // 4. 执行SQL,返回结果集
            ResultSet rs = stmt.executeQuery(strSQL);
            // 5. 遍历结果集
            while (rs.next()) {
                // 定义当前行向量
                Vector<String> currentRow = new Vector();
                // 利用当前记录字段值设置当前行向量的元素值
                currentRow.addElement(rs.getString("性别"));
                currentRow.addElement(rs.getInt("人数") + "");
                // 将当前行向量添加到行集向量
                rows.addElement(currentRow);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回行集向量
        return rows;
    }

    /**
     * 按班级统计学生人数
     *
     * @return 统计结果向量
     */
    @Override
    public Vector findRowsByClass() {
        // 定义行集向量
        Vector rows = new Vector();

        // 1. 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "select class as '班级', count(*) as '人数'"
                + " from t_student group by class order by class desc";
        try {
            // 3. 创建语句对象
            Statement stmt = conn.createStatement();
            // 4. 执行SQL,返回结果集
            ResultSet rs = stmt.executeQuery(strSQL);
            // 5. 遍历结果集
            while (rs.next()) {
                // 定义当前行向量
                Vector<String> currentRow = new Vector();
                // 利用当前记录字段值设置当前行向量的元素值
                currentRow.addElement(rs.getString("班级"));
                currentRow.addElement(rs.getInt("人数") + "");
                // 将当前行向量添加到行集向量
                rows.addElement(currentRow);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回行集向量
        return rows;
    }

    /**
     * 按系部统计学生人数
     *
     * @return 统计结果向量
     */
    @Override
    public Vector findRowsByDepartment() {
        // 定义行集向量
        Vector rows = new Vector();

        // 1. 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "select department as '系部', count(*) as '人数'"
                + " from t_student group by department order by department desc";
        try {
            // 3. 创建语句对象
            Statement stmt = conn.createStatement();
            // 4. 执行SQL,返回结果集
            ResultSet rs = stmt.executeQuery(strSQL);
            // 5. 遍历结果集
            while (rs.next()) {
                // 定义当前行向量
                Vector<String> currentRow = new Vector();
                // 利用当前记录字段值设置当前行向量的元素值
                currentRow.addElement(rs.getString("系部"));
                currentRow.addElement(rs.getInt("人数") + "");
                // 将当前行向量添加到行集向量
                rows.addElement(currentRow);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回行集向量
        return rows;
    }
}


}

13.对StudentDaoImpl进行单元测试

在这里插入图片描述

(1) 编写testInsert方法

在这里插入图片描述
运行程序,查看结果:
在这里插入图片描述
打开数据表,查看运行结果:
在这里插入图片描述

(2)编写testDeleteById()方法

在这里插入图片描述
运行程序,查看结果:
在这里插入图片描述
查看数据表中数据:
这是未删除之前的数据表:
在这里插入图片描述
这是删除以后的数据表:
在这里插入图片描述

(3)编写testDeleteByClass()方法

在这里插入图片描述
运行程序,查看结果:
在这里插入图片描述

(4)编写testFindByName()方法

在这里插入图片描述
运行程序,查看结果:
在这里插入图片描述
将代码中的人名修改为数据表中包含的人名,即可查询出记录
在这里插入图片描述
使用该方法,还可以进行类似于SQL语句中模糊查询的使用结果
在这里插入图片描述
在这里插入图片描述

(5)编写testFindAll()方法

  @Test
    public void testFindAll(){
        //调用学生数据访问对象的查找全部方法
        List<Student> students = dao.findAll();
        for(Student student:students){
            System.out.println(student);
        }
    }

查看运行结果:在这里插入图片描述

(6)编写testFindRowsBySex()方法

@Test
    public void testFindRowsBySex(){
        //调用学生数据访问对象的按性别统计人数方法
        Vector rows = dao.findRowsBySex();
        //获取向量的跌代器
        Iterator iterator = rows.iterator();
        //遍历迭代器
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }

    }

在这里插入图片描述

(7) 编写testDeleteByDepartment()方法

    @Test
    public void testDeleteByDepartment(){
        String department = "国际学院";
        int count = dao.deleteByDepartment(department);
        if (count > 0){
            System.out.println("恭喜,删除记录成功!");
        }else{
            System.out.println("遗憾,删除记录失败!");
        }
    }

运行程序,查看结果:
在这里插入图片描述

(8)编写testUpdate()方法

  @Test
    public void testUpdate(){
        Student student = new Student();
        student.setId("20190142");
        student.setName("郭德纲");
        student.setSex("男");
        student.setAge(20);
        student.setDepartment("人文学院");//由机械工程学院修改为人文学院
        student.setClazz("19小学教育1班");//由19机电一体化1班修改为小学教育1班
        student.setTelephone("12346578756");
        int count = dao.update(student);
        if (count > 0){
            System.out.println("恭喜,更新学生记录成功");
            System.out.println(student);
        }else{
            System.out.println("遗憾,更新数据失败");
        }

    }

运行结果:
在这里插入图片描述

(9)编写testFindById()方法

  @Test
    public void FindById(){
        String id = "20190138";
        List<Student> students = Collections.singletonList(dao.findById(id));
        if (students.size() > 0){
            for (Student student:students){
                System.out.println(student);
            }
        }else{
            System.err.println("温馨提示:没有这个ID,请重新输入");
        }


    }

运行结果:
在这里插入图片描述

(10)编写testFindByClass()方法

  @Test
    public void FindByClass(){
        String clazz = "19语教2班";
        List<Student> students = dao.findByClass(clazz);
        if (students.size() > 0){
            for (Student student:students){
                System.out.println(student);
            }
        }else{
            System.err.println("温馨提示:没有这个班级,请重新输入");
        }

    }

运行结果:
在这里插入图片描述

(11)编写testFindByDepartment()方法

  @Test
    public void testFindByDepartment(){
        String department = "信息工程学院";
        List<Student> students = dao.findByDepartment(department);
        //判断列表里是否有元素
        if (students.size() > 0){
            for (Student student:students){
                System.out.println(student);
            }
        }else{
            System.err.println("温馨提示:查无此人");
        }
    }

运行结果:
在这里插入图片描述

(12)编写testFindRowsByClass()方法

   @Test
    public void testFindRowsByClass(){
        //调用学生数据访问对象的按班级统计人数方法
        Vector rows = dao.findRowsByClass();
        //获取向量的跌代器
        Iterator iterator = rows.iterator();
        //遍历迭代器
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

运行结果:
在这里插入图片描述

(13)编写testFindRowsByDepartment()方法

    @Test
    public void testFindRowsByDepartment(){
        //调用学生数据访问对象的按学院统计人数方法
        Vector rows = dao.findRowsByDepartment();
        //获取向量的跌代器
        Iterator iterator = rows.iterator();
        //遍历迭代器
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

运行结果:
在这里插入图片描述

14.创建用户数据访问接口实现类

在这里插入图片描述

package net.lyq.student.dao.impl;

import net.lyq.student.bean.User;
import net.lyq.student.dao.UserDao;
import net.lyq.student.dbutil.ConnectionManager;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能:用户数据访问接口实现类
 * 作者:华卫
 * 日期:2020年06月05日
 */
public class UserDaoImpl implements UserDao {
    /**
     * 插入用户记录
     *
     * @param user
     * @return 插入记录数
     */
    @Override
    public int insert(User user) {
        // 定义插入记录数
        int count = 0;

        // 1. 获得数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "insert into t_user (username, password, telephone, register_time)"
                + " values (?, ?, ?, ?)";

        // 不允许用户表里插入两条用户名相同的记录
        if (!isUsernameExisted(user.getUsername())) {
            try {
                // 3. 创建预备语句对象
                PreparedStatement pstmt = conn.prepareStatement(strSQL);
                // 4. 设置占位符的值
                pstmt.setString(1, user.getUsername());
                pstmt.setString(2, user.getPassword());
                pstmt.setString(3, user.getTelephone());
                pstmt.setTimestamp(4, new Timestamp(user.getRegisterTime().getTime()));
                // 5. 执行SQL,返回插入记录数
                count = pstmt.executeUpdate();
                // 6. 关闭预备语句对象
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                // 关闭数据库连接
                ConnectionManager.closeConnection(conn);
            }
        }

        // 返回插入记录数
        return count;
    }

    /**
     * 按id删除用户记录
     *
     * @param id
     * @return 删除记录数
     */
    @Override
    public int deleteById(int id) {
        // 定义删除记录数
        int count = 0;

        // 1. 获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "delete from t_user where id = ?";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setInt(1, id);
            // 5. 执行SQL,返回删除记录数
            count = pstmt.executeUpdate();
            // 6. 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回删除记录数
        return count;
    }

    /**
     * 更新用户记录
     *
     * @param user
     * @return 更新记录数
     */
    @Override
    public int update(User user) {
        // 定义更新记录数
        int count = 0;

        // 1. 获得数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "update t_user set username = ?, password = ?, telephone = ?,"
                + " register_time = ? where id = ?";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getTelephone());
            pstmt.setTimestamp(4, new Timestamp(user.getRegisterTime().getTime()));
            pstmt.setInt(5, user.getId());
            // 5. 执行SQL,返回更新记录数
            count = pstmt.executeUpdate();
            // 6. 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回更新记录数
        return count;
    }

    /**
     * 按id查询用户
     *
     * @param id
     * @return 用户实体
     */
    @Override
    public User findById(int id) {
        // 声明用户对象
        User user = null;

        // 1. 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "select * from t_user where id = ?";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setInt(1, id);
            // 5. 执行SQL,返回结果集
            ResultSet rs = pstmt.executeQuery();
            // 6. 判断结果集是否有记录
            if (rs.next()) {
                // 创建用户实体
                user = new User();
                // 利用当前记录各字段值设置用户实体属性
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setTelephone(rs.getString("telephone"));
                user.setRegisterTime(rs.getTimestamp("register_time"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回用户对象
        return user;
    }

    /**
     * 查询所有用户
     *
     * @return 用户列表
     */
    @Override
    public List<User> findAll() {
        // 声明用户列表
        List<User> users = new ArrayList<User>();

        // 1. 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "select * from t_user";
        try {
            // 3. 创建语句对象
            Statement stmt = conn.createStatement();
            // 4. 执行SQL,返回结果集
            ResultSet rs = stmt.executeQuery(strSQL);
            // 5. 遍历结果集
            while (rs.next()) {
                // 创建用户实体
                User user = new User();
                // 利用当前记录各字段值设置用户实体属性
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setTelephone(rs.getString("telephone"));
                user.setRegisterTime(rs.getTimestamp("register_time"));
                // 将实体添加到用户列表
                users.add(user);
            }
            // 6. 关闭结果集
            rs.close();
            // 7. 关闭语句对象
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回用户列表
        return users;
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return 登录用户实体
     */
    @Override
    public User login(String username, String password) {
        // 声明用户对象
        User user = null;

        // 1. 获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "select * from t_user where username = ? and password = ?";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            // 5. 执行SQL,返回结果集
            ResultSet rs = pstmt.executeQuery();
            // 6. 判断结果集是否有记录
            if (rs.next()) {
                // 实例化用户
                user = new User();
                // 利用当前记录各字段值设置用户实体属性
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setTelephone(rs.getString("telephone"));
                user.setRegisterTime(rs.getTimestamp("register_time"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回用户对象
        return user;
    }

    @Override
    public boolean isUsernameExisted(String username) {
        // 定义存在与否变量
        boolean existed = false;

        // 1. 获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 2. 定义SQL字符串
        String strSQL = "select * from t_user where username = ?";
        try {
            // 3. 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 4. 设置占位符的值
            pstmt.setString(1, username);
            // 5. 执行SQL,返回结果集
            ResultSet rs = pstmt.executeQuery();
            // 6. 判断结果集是否有记录
            if (rs.next()) {
                existed = true;
            }
            // 7. 关闭预备语句对象
            pstmt.close();
            // 8. 关闭结果集对象
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回存在与否变量
        return existed;
    }
}

15.单元测试:对UserDaoImpl进行单元测试

在这里插入图片描述

(1)编写方法testFindById()

在这里插入图片描述
运行结果:
在这里插入图片描述

(2)编写方法testLogin()

在这里插入图片描述
运行结果:
在这里插入图片描述

(3)编写测试方法testIsUsernameExisted()

在这里插入图片描述
运行结果:
在这里插入图片描述

(4)编写测试方法testInsert()

在这里插入图片描述
运行结果:
在这里插入图片描述

(5)编写测试方法testDeleteById()

在这里插入图片描述
运行结果如下:
由于输入的id已经被删除,所以结果会显示出记录删除失败,修改id即可删除成功
在这里插入图片描述

(6)编写testUpdate()方法

**加粗样式
运行结果:
在这里插入图片描述
数据表结果:
在这里插入图片描述

(7)编写testFindAll()方法

在这里插入图片描述
运行结果:
在这里插入图片描述

总结

这次博客的内容,包括了两次课的任务,最近两次的实训任务都比较多,所以花费了较多时间,在完成这次任务的途中也出现了很多问题,大多时间是由于打字速度过快,单词出现拼写错误,影响了后面代码的运行,也花了很多时间改正前几次任务中的单词拼写问题,由此在以后编写层层相扣的项目时,一定要注意细节,一些细节问题可能会导致后面花很多时间去改正。在涉及数据库操作时,编写代码一定要与数据库中的字符类型相对应,基础一定要打好,后面才会更快完成任务。

猜你喜欢

转载自blog.csdn.net/weixin_46705517/article/details/107098716