【Java实训日志5】

文章目录

八、项目开发实训步骤

(七)创建数据访问接口实现类

  • net.hw.student.dao包里创建impl子包
    -

1、创建学校数据访问接口实体类

  • net.hw.student.dao包里创建CollegeDaoImpl
    在这里插入图片描述
  • 实现CollegeDao接口
    在这里插入图片描述

在这里插入图片描述

(1)编写按标识符查询学校记录方法和更新学校记录方法
package net.huawei.student.dao.impl;

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

import java.sql.*;

/**
 * 功能
 * 作者:小刚
 * 日期:2023年06月14日
 */
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 = new College();
                // 利用当前记录字段值设置学校对象属性值
                college.setId(rs.getInt("id"));
                college.setName(rs.getString("name"));
                college.setPresident(rs.getString("president"));
                college.setStartTime(rs.getTimestamp("stsrt_time"));
                college.setEmail(rs.getString("email"));
                college.setAddress(rs.getString("address"));
                college.setProfile(rs.getString("profile"));
            }

        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
        }
            ConnectionManager.closeConnection(conn);
        return college;
    }

    @Override // 更新学校记录
    public int update(College college) {
        // 定义更新记录数
        int count = 0;
        //
        Connection conn = ConnectionManager.getConnection();
        //
        String strSQL = "UPDATE t_college SET name = ?, president = ?,start_time = ?, email = ?, address = ?, 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.getEmail());
            pstmt.setString(5, college.getAddress());
            pstmt.setString(6, college.getProfile());
            pstmt.setInt(7, college.getId());
            // 执行更新操作,返回更新记录数
            count = pstmt.executeUpdate();
            //关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn);
        }
        return count;
    }
}

1_、测试学校数据访问接口实现类

  • test创建net.huawei.student.dao.imp
  • net.huawei.student.dao.imp包创建TestCollegeDaoImpl
    在这里插入图片描述
(1)编写测试按标识符查询学校记录方法
package net.huawei.student.dao.impl;

import net.huawei.student.bean.College;
import net.huawei.student.dao.CollegeDao;
import org.junit.Test;

/**
 * 功能
 * 作者:小刚
 * 日期:2023年06月14日
 */
public class TestCollegeDaoImpl {
    @Test //测试按标识符查询学校记录
    public void testFindById(){
        // 定义标识符变量
        int id = 9;
        // 创建学校数据访问接口对象
        CollegeDao collegeDao = new CollegeDaoImpl();
        //
        College college = collegeDao.findById(id);
        // 判断插询是否成功
        if (college != null) {
            System.out.println("标识符:" + college.getId());
            System.out.println("学校名称:" + college.getName());
            System.out.println("校长:" + college.getPresident());
            System.out.println("建校时间:" + college.getStartTime());
            System.out.println("电子邮箱:" + college.getEmail());
            System.out.println("通信地址:" + college.getAddress());
            System.out.println("学校概况:" + college.getProfile());
        }else{
            System.out.println("标识符[" + id + "]的学校记录不存在~");
        }
    }
}

  • 运行,查看结果
    在这里插入图片描述
  • 修改标识符变量值
    在这里插入图片描述
(2)编写测试更新学校记录方法
@Test // 测试更新学校记录                                                                        
private void testUpdate(){                                                               
    // 创建学校数据访问接口对象                                                                      
    CollegeDao collegeDao = new CollegeDaoImpl();                                        
    //获取标识符为1的学校记录                                                                       
    College college = collegeDao.findById(1);                                            
    //输出更新前的学校信息                                                                         
    System.out.println("更新前:" + college);                                                
    //                                                                                   
    college.setName("泸职院");                                                              
    college.setPresident("么么哒");                                                         
    college.setProfile("");                                                              
    // 调用学校更新记录方法                                                                        
    int count = collegeDao.update(college);                                              
    //                                                                                   
    if (count > 0){                                                                      
        System.out.println("恭喜,学习记录更新成功");                                               
        System.out.println("更新后:" + collegeDao.findById(1));                             
    }else {                                                                              
        System.out.println("遗憾,学校记录更新失败");                                               
    }                                                                                    
                                                                                         
}                                                                                        
  • 运行结果
    在这里插入图片描述

2、创建状态数据访问接口实体类

  • net.hw.student.dao包里创建StatusDaoImpl
    -在这里插入图片描述
(1)编写按标识符查询状态记录方法
package net.huawei.student.dao.impl;

import net.huawei.student.bean.Status;
import net.huawei.student.dao.StatusDao;
import net.huawei.student.dbutil.ConnectionManager;

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

/**
 * 功能
 * 作者:小刚
 * 日期:2023年06月14日
 */
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 {
            PreparedStatement pstmt = conn.prepareStatement( strSQL);
            //4.设置占位符的值
            pstmt.setInt(  1,id);
            //5.执行soL查询,返回结果集
            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();
            rs.close();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn) ;
        }

        //返回状态对象
        return status;
    }
(2)编写更新状态记录方法
 @Override
    public int update(Status status) {
        int count = 1;
        // 1.获得数据库连接
        Connection conn = ConnectionManager.getConnection();
        //2.定义SQL字符串
        String strsQL = "update t_status set college - ?, version - ?, author = ?,+telephone = ?, address = ?, email = ? where id = ?";
        try {
            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) {
            System.out.println(e.getMessage());
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection( conn) ;
        }
        //返回更新记录数
        return count;
    }
}

2_,测试状态数据访问接口实现类

  • net.huawei.student.dao.imp包创建TestStatusDaoImpl
    在这里插入图片描述
(1)编写测试按标识符查询状态记录方法
package net.huawei.student.dao.impl;

import net.huawei.student.bean.Status;
import net.huawei.student.dao.StatusDao;
import org.junit.Test;

/**
 * 功能
 * 作者:小刚
 * 日期:2023年06月14日
 */
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());
    }
(2)编写测试更新状态记录方法
@Test // 更新记录
    public void testUpdate(){
        //调用状态数据访问对象的查询方法
        Status status = dao.findById(1);
        //修改状态对象的属性
        status.setAuthor("无剑");
        status.setTelephone( "13845456780" );
        status.setEmail( "ghf1213" ) ;
        //调用状态数据访问对象的更新方法
        int count = dao.update(status);
        //判断状态更新是否成功
        if(count > 0){
            System.out.println("状态记录更新成功!");
            System.out.println(dao.findById( 1));
        }else{
            System.out.println("状态记录更新失败!");
        }
    }
}
  • 查看运行结果
    在这里插入图片描述

3,创建学生数据访问接口实现类

  • net.hw.student.dao包里创建StudentDaoImpl
    在这里插入图片描述
(1)编写插入学生记录的方法
package net.huawei.student.dao.impl;

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

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

/**
 * 功能
 * 作者:小刚
 * 日期:2023年06月15日
 */
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 {
            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();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
            ;
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        return count;
    }
(2)编写按id删除学生记录的方法
   @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) {
            System.err.println(e.getMessage());
            ;
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        //返回删除记录数
        return count;
    }
(3)编写按班级删除学生记录的方法
 @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) {
            System.err.println(e.getMessage());
            ;
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        return count;
    }
(4)编写按系部删除学生记录的方法
 @Override
    public int deleteByDepartment(String department) {
        //定义删除记录数
        int count = 6;
        //1.获得数据库连接
        Connection conn = ConnectionManager.getConnection();
        //2.定义SQL字符串
        String strSQL = "delete from t_student where department - ?";
        try {
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
        } catch (SQLException e) {
            System.err.println(e.getMessage());
            ;
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        //返回删除记录数
        return count;
    }
(5)定义更新学生记录的方法
@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) {
            System.err.println(e.getMessage());
            ;
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        //返回更新记录数
        return count;
    }
(6)编写按id查询学生记录的方法
@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) {
            System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn);
        }
        return student;
    }
(7)编写按姓名查询学生记录的方法
@Override
    public List<Student> findByName(String name) {
        //声明学生列表
        List<Student> students = new ArrayList<>();
        //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) {
            System.out.println(e.getMessage());
            ;
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        //返回学生列表
        return students;
    }
(8)编写按班级查询学生记录的方法
@Override
    public List<Student> findByClass(String clazz) {
        //声明学生列表
        List<Student> students = new ArrayList<>();
        //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) {
            System.err.println(e.getMessage());
            ;
        } finally {
            ConnectionManager.closeConnection(conn);
        }
        //返回学生列表
        return students;
    }
(9)编写按系部查询学生记录的方法
@Override
    public List<Student> findByDepartment(String department) {
        // 声明学生列表
        List<Student> students = new ArrayList<>();

        //1.获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 2.定义SQL字符串
        String strSQL = "select * from t_student where department like ?";
        // 3.
        try {

            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) {
            System.err.println(e.getMessage());
            ;
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        // 返回学生列表
        return students;
    }


(10)编写查询全部学生记录的方法
    @Override
    public List<Student> findAll() {
        //声明学生列表
        List<Student> students = new ArrayList<>();
        //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) {
            System.err.println(e.getMessage());
            ;
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        //返回学生列表
        return students;
    }
(11)编写按性别统计学生人数
@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) {
            System.err.println(e.getMessage());
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        //返回行集向量
        return rows;
    }
(12)编写按班级统计学生人数
@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) {
            System.err.println(e.getMessage());
            ;
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        //返回行集向量
        return rows;
    }
(13)编写按系部统计学生人数
@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) {
            System.err.println(e.getMessage());
            ;
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        // 返回行集向量
        return rows;
    }
}

3_、测试学生数据访问接口实现类

  • net.huawei.student.dao.imp包创建TestStudentDaoImpl
    在这里插入图片描述
(1)编写测试插入学生记录的方法
package net.huawei.student.dao.impl;

import net.huawei.student.bean.Student;
import net.huawei.student.dao.StudentDao;
import org.junit.Test;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

/**
 * 功能
 * 作者:小刚
 * 日期:2023年06月15日
 */
public class TestStudentDaoImpl {
    //定义学生数据访问对象
    StudentDao dao = new StudentDaoImpl();

    @Test
    public void testInsert() {
        //创建学生对象
        Student student = new Student();
//设置学生对象属性
        student.setId("192042099");
        student.setName("张晓慧");
        student.setSex("女");
        student.setAge(19);
        student.setDepartment("艺术传媒学院");
        student.setClazz("2019数媒3班");
        student.setTelephone("15890674568");
        //调用学生数据访问对象的插入方法
        int count = dao.insert(student);
        //判断学生记录是否插入成功
        if (count > 0) {
            System.out.println("恭喜,学生记录插入成功! ");
            System.out.println(dao.findById(student.getId()));
        } else {
            System.out.println("遗憾,学生记录插入失败! ");
        }
    }
(2)编写测试按id删除学生记录的方法
@Test
    public void testDeleteById() {
        String id = "19101001";
        //调用学生数据访问对象的按id删除方法
        int count = dao.deleteById(id);
        //判断学生记录是否删除成功
        if (count > 0) {
            System.out.println("恭喜,学生记录除成功! ");
        } else {
            System.out.println("遗憾,学生记录删除失败! ");
        }
    }
(3)编写测试按班级删除学生记录的方法
 @Test
    public void testDeleteByClass() {
        String clazz = "2019小教3班";
        //调用学生数据访问对象的按班级删除方法
        int count = dao.deleteByClass(clazz);
        if (count > 0) {
            System.out.println("恭喜, [" + clazz + "]学生记录除成功! ");
        } else {
            System.out.println("遗憾,[" + clazz + "]学生记录除失败! ");
        }
    }
(4)编写测试按系部删除学生记录的方法
@Test
    public void testFindByName() {
        String name = "张";
        //调用学生数据访问对象的按姓名查找方法
        List<Student> students = dao.findByName(name);
        //判断列表里是否有元素
        if (students.size() > 0) {
            //通过增强for循环遍历学生列表
            for (Student student : students) {
                System.out.println(student);
            }
        } else {
            System.out.println("温馨提示:无此人! ");
        }
    }
(5)编写测试更新学生记录的方法
 @Test
    public void testFindA1l() {
        //调用学生数据访问对象的查找全部方法
        List<Student> students = dao.findAll();
        //通过增强for循环遍历学生列表
        for (Student student : students) {
            System.out.println(student);
        }
    }
(6)编写测试按id查询学生记录的方法
@Test
    public void testFindRowsBySex() {
        //调用学生数据访问对象的按性别统计人数方法
        Vector rows = dao.findRowsBySex();
        //获取向量的迭代器
        Iterator iterator = rows.iterator();
        //遍历迭代器
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
(7)编写测试按姓名查询学生记录的方法
@Test
    public void testDeleteByDepartment() {
        String department = "电子工程学院";

        int count = dao.deleteByDepartment(department);
        if (count > 0) {
            System.out.println("恭喜," + department + "的学生记录删除成功!!!");
        } else {
            System.out.println("What a pity!学生记录删除失败!!!");
        }
    }
(8)编写测试按班级查询学生记录的方法
@Test
    public void testUpdate() {
        StudentDao studentDao = new StudentDaoImpl();
        Student student = studentDao.findById("19204196");
        System.out.println("更新前:" + student);
        student.setAge(20);
        student.setTelephone("11111000001");
        student.setDepartment("怨种学院");
        int count = studentDao.update(student);
        if (count > 0) {
            System.out.println("更新成功!!!");
            System.out.println("更新后:" + studentDao.findById("19204196"));
        } else {
            System.out.println("What a pity!更新失败!!!");
        }
    }
(9)编写测试按系部查询学生记录的方法
@Test
    public void testFindById() {
        String id = "19204196";

        Student student = dao.findById(id);
        if (student != null) {
            System.out.println("查询到了:" + student);
        } else {
            System.out.println("What a pity!查询失败!!!");
        }
    }
(10)编写测试查询全部学生记录的方法
@Test
    public void testFindByClass() {
        String clazz = "2022机电3班";

        List<Student> students = dao.findByClass(clazz);
        if (students.size() > 0) {
            for (Student student : students) {
                System.out.println(student);
            }
        } else {
            System.out.println("查询失败!!!");
        }
    }
(11)编写测试按性别统计学生人数
@Test
    public void testFindByClass() {
        String clazz = "2022机电3班";

        List<Student> students = dao.findByClass(clazz);
        if (students.size() > 0) {
            for (Student student : students) {
                System.out.println(student);
            }
        } else {
            System.out.println("查询失败!!!");
        }
    }
(12)编写测试按班级统计学生人数
@Test
    public void testFindRowsByClass() {

        Vector rows = dao.findRowsByClass();
        Iterator iterator = rows.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
(13)编写测试按系部统计学生人数
@Test
    public void testFindRowsByDepartment() {

        Vector rows = dao.findRowsByDepartment();
        Iterator iterator = rows.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

4、创建用户数据访问接口实现类

  • net.hw.student.dao包里创建UserDaoImpl
    在这里插入图片描述
(1)编写插入用户记录
package net.huawei.student.dao.impl;

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

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

/**
 * 功能∶用户数据访问接口实现类*作者:华卫
 * 日期:2020年06月05日
 */
public class UserDaoImpl implements UserDao {
    @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) {
                System.err.println(e.getMessage());
                ;
            } finally {
                //关闭数据库连接
                ConnectionManager.closeConnection(conn);
            }
        }
        //返回插入记录数
        return count;
    }
(2)编写删除用户记录
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) {
            System.err.println(e.getMessage());
            ;
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        //返回删除记录数
        return count;
    }
(3)编写更新用户记录
@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.执行soL, 返回更新记录数
            count = pstmt.executeUpdate();
            // 6.关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
            ;
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        //返回更新记录数
        return count;
    }
(4)编写查询用户记录
@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) {
            System.err.println(e.getMessage());
            ;
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        //返回用户对象r
        return user;
    }
(5)编写查询所有用户记录
@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) {
            System.err.println(e.getMessage());
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        //返回用户列表
        return users;
    }
(6)编写用户登录记录
@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.执行soL ,返回结果集
            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) {
            System.out.println(e.getMessage());
            ;
        } finally {
            //关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        //返回用户对象
        return user;
    }
(7)编写查看是否有记录
@Override
    public boolean isUsernameExisted(String username) {
        boolean existed = false;

        Connection conn = ConnectionManager.getConnection();

        String strSQL = "SELECT * FROM t_user WHERE username = ?";
        try {
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                existed = true;
            }
            pstmt.close();
            rs.close();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn);
        }
        return existed;
    }
}

4_、测试用户数据访问接口实现类

  • net.huawei.student.dao.imp包创建TestUserDaoImpl
    在这里插入图片描述
(1)编写测试插入用户记录
package net.huawei.student.dao.impl;

import net.huawei.student.bean.User;
import net.huawei.student.dao.UserDao;
import org.junit.Test;

import java.util.Date;
import java.util.List;

/**
 * 功能:
 * 作者:小刚
 * 日期:2023年06月16日
 */
public class TestUserDaoImpl {
    UserDao dao = new UserDaoImpl();
	@Test
    public void testInsert() {
        User user = new User();
        user.setUsername("坤坤");
        user.setPassword("123654");
        user.setTelephone("963874521");
        user.setRegisterTime(new Date());
        int count = dao.insert(user);
        if (count > 0) {
            System.out.println("恭喜!!!用户记录插入成功!");
            System.out.println(dao.findById(dao.findAll().size()));
        } else {
            System.out.println("插入失败!!!");
        }
    }
(2)编写测试删除用户记录
@Test
    public void testDeleteById() {
        int id = 9;
        int count = dao.deleteById(id);
        if (count != 0) {
            System.out.println("删除用户记录成功!!!");
        } else {
            System.out.println("删除记录失败!!!");
        }
    }
(3)编写测试更新用户记录
@Test
    public void testUpdate() {
        UserDao userdao = new UserDaoImpl();
        User user = userdao.findById(1);
        System.out.println("更新前:" + user);
        user.setTelephone("11111000111");
        user.setUsername("GGboard");
        int count = userdao.update(user);
        if (count > 0) {
            System.out.println("更新成功!!!");
            System.out.println("更新后:" + userdao.findById(1));
        } else {
            System.out.println("更新失败!!!");
        }
    }
(4)编写测试查询用户记录
@Test
    public void testFindById() {
        User user = dao.findById(1);
        System.out.println("用户名:" + user.getUsername());
        System.out.println("密码:" + user.getPassword());
        System.out.println("电话:" + user.getTelephone());
        System.out.println("注册时间:" + user.getRegisterTime());
    }
(5)编写测试查询所有用户记录
@Test
    public void testFindAll() {

        List<User> users = dao.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }
(6)编写测试用户登录记录
@Test
    public void testLogin() {
        String username, password;
        username = "hhp";
        password = "kkk";
        User user = dao.login(username, password);
        if (user != null) {
            System.out.println("用户名与密码正确,登录成功!!!");
        } else {
            System.out.println("登录失败!用户名或密码输入错误!!!");
        }
    }
(7)编写测试查看是否有记录
@Test
    public void testLogin() {
        String username, password;
        username = "hhp";
        password = "kkk";
        User user = dao.login(username, password);
        if (user != null) {
            System.out.println("用户名与密码正确,登录成功!!!");
        } else {
            System.out.println("登录失败!用户名或密码输入错误!!!");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值