首页 > 编程语言 >12.23博客 java实战2019年试题

12.23博客 java实战2019年试题

时间:2024-12-27 14:53:07浏览次数:10  
标签:preparedStatement java 12.23 DB department 2019 employee import

今天继续完成建民老师发的2019年试题
DAO 层设计(数据访问对象,用于数据库操作)
员工信息
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class EmployeeDAO {
private static final String DB_URL;
private static final String DB_USERNAME;
private static final String DB_PASSWORD;

static {
    Properties properties = new Properties();
    try {
        properties.load(EmployeeDAO.class.getClassLoader().getResourceAsStream("db.properties"));
        DB_URL = properties.getProperty("db.url");
        DB_USERNAME = properties.getProperty("db.username");
        DB_PASSWORD = properties.getProperty("db.password");
    } catch (Exception e) {
        throw new RuntimeException("数据库配置加载失败", e);
    }
}

// 新增员工基本信息
public void addEmployee(Employee employee) {
    try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
         PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO employee_basic_info (job_id, name, sex, birthday, department, role, password) VALUES (?,?,?,?,?,?,?)")) {
        preparedStatement.setString(1, employee.getJobId());
        preparedStatement.setString(2, employee.getName());
        preparedStatement.setString(3, employee.getSex());
        preparedStatement.setString(4, employee.getBirthday());
        preparedStatement.setString(5, employee.getDepartment());
        preparedStatement.setString(6, employee.getRole());
        preparedStatement.setString(7, employee.getPassword());
        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

// 修改员工基本信息(除工号外可修改部分字段)
public void updateEmployee(Employee employee) {
    try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
         PreparedStatement preparedStatement = connection.prepareStatement("UPDATE employee_basic_info SET name =?, sex =?, birthday =? WHERE job_id =?")) {
        preparedStatement.setString(1, employee.getName());
        preparedStatement.setString(2, employee.getSex());
        preparedStatement.setString(3, employee.getBirthday());
        preparedStatement.setString(4, employee.getJobId());
        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

// 删除员工基本信息
public void deleteEmployee(String jobId) {
    try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
         PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM employee_basic_info WHERE job_id =?")) {
        preparedStatement.setString(1, jobId);
        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

// 根据工号查询员工信息
public Employee getEmployeeByJobId(String jobId) {
    try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
         PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM employee_basic_info WHERE job_id =?")) {
        preparedStatement.setString(1, jobId);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            Employee employee = new Employee();
            employee.setJobId(resultSet.getString("job_id"));
            employee.setName(resultSet.getString("name"));
            employee.setSex(resultSet.getString("sex"));
            employee.setBirthday(resultSet.getString("birthday"));
            employee.setDepartment(resultSet.getString("department"));
            employee.setRole(resultSet.getString("role"));
            employee.setPassword(resultSet.getString("password"));
            return employee;
        }
        return null;
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

// 查询所有员工信息(可用于部门经理查看本部门员工等情况)
public List<Employee> getAllEmployees() {
    List<Employee> employees = new ArrayList<>();
    try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
         PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM employee_basic_info")) {
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            Employee employee = new Employee();
            // 设置员工信息属性,同 getEmployeeByJobId 中从 ResultSet 取值并设置属性的过程
            employees.add(employee);
        }
        return employees;
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

}
部门信息
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class DepartmentDAO {
private static final String DB_URL;
private static final String DB_USERNAME;
private static final String DB_PASSWORD;

static {
    Properties properties = new Properties();
    try {
        properties.load(DepartmentDAO.class.getClassLoader().getResourceAsStream("db.properties"));
        DB_URL = properties.getProperty("db.url");
        DB_USERNAME = properties.getProperty("db.username");
        DB_PASSWORD = properties.getProperty("db.password");
    } catch (Exception e) {
        throw new RuntimeException("数据库配置加载失败", e);
    }
}

// 新增部门基本信息
public void addDepartment(Department department) {
    try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
         PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO department_basic_info (department_id, department_name) VALUES (?,?)")) {
        preparedStatement.setString(1, department.getDepartmentId());
        preparedStatement.setString(2, department.getDepartmentName());
        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

// 修改部门基本信息(部门名称)
public void updateDepartment(Department department) {
    try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
         PreparedStatement preparedStatement = connection.prepareStatement("UPDATE department_basic_info SET department_name =? WHERE department_id =?")) {
        preparedStatement.setString(1, department.getDepartmentName());
        preparedStatement.setString(2, department.getDepartmentId());
        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

// 删除部门基本信息(需判断部门下是否有员工)
public void deleteDepartment(String departmentId) {
    // 先查询该部门是否还有员工,如果有则不允许删除
    if (hasEmployeesInDepartment(departmentId)) {
        return;
    }
    try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
         PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM department_basic_info WHERE department_id =?")) {
        preparedStatement.setString(1, departmentId);
        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

private boolean hasEmployeesInDepartment(String departmentId) {
    try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
         PreparedStatement preparedStatement = connection.prepareStatement("SELECT COUNT(*) FROM employee_basic_info WHERE department = (SELECT department_name FROM department_basic_info WHERE department_id =?)")) {
        preparedStatement.setString(1, departmentId);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            int count = resultSet.getInt(1);
            return count > 0;
        }
        return false;
    } catch (SQLException e) {
        e.printStackTrace();
        return false;
    }
}

// 查询所有部门信息
public List<Department> getAllDepartments() {
    List<Department> departments = new ArrayList<>();
    try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
         PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM department_basic_info")) {
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            Department department = new Department();
            department.setDepartmentId(resultSet.getString("department_id"));
            department.setDepartmentName(resultSet.getString("department_name"));
            departments.add(department);
        }
        return departments;
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

// 根据部门编号查询部门信息
public Department getDepartmentById(String departmentId) {
    try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
         PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM department_basic_info WHERE department_id =?")) {
        preparedStatement.setString(1, departmentId);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            Department department = new Department();
            department.setDepartmentId(resultSet.getString("department_id"));
            department.setDepartmentName(resultSet.getString("department_name"));
            return department;
        }
        return null;
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

}
考勤记录
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class AttendanceRecordDAO {
private static final String DB_URL;
private static final String DB_USERNAME;
private static final String DB_PASSWORD;

static {
    Properties properties = new Properties();
    try {
        properties.load(AttendanceRecordDAO.class.getClassLoader().getResourceAsStream("db.properties"));
        DB_URL = properties.getProperty("db.url");
        DB_USERNAME = properties.getProperty("db.username");
        DB_PASSWORD = properties.getProperty("db.password");
    } catch (Exception e) {
        throw new RuntimeException("数据库配置加载失败", e);
    }
}

// 新增考勤记录
public void addAttendanceRecord(AttendanceRecord record) {
    try (Connection connection = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
         PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO attendance_record (attendance_time, job_id, name, sex, birthday, department, attendance_type) VALUES (?,?,?,?,?,?,?)")) {
        preparedStatement.setTimestamp(1, new java.sql.Timestamp(record.getAttendanceTime().getTime()));
        preparedStatement.setString(2, record.getJobId());
        preparedStatement.setString(3, record.getName());
        preparedStatement.setString(4, record.getSex());
        preparedStatement.setString(5, record.getBirthday());
        preparedStatement.setString(6, record.getDepartment());
        preparedStatement.setString(7, record.getAttendanceType());
        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Servlet 设计与实现
登录
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String jobId = request.getParameter("job_id");
String password = request.getParameter("password");
// 调用 EmployeeDAO 验证用户登录信息,根据角色跳转到相应页面
// 示例代码,实际需完善验证逻辑和页面跳转逻辑
if ("admin".equals(jobId) && "admin123".equals(password)) {
// 管理员登录,跳转到管理员功能页
response.sendRedirect("admin.jsp");
} else {
// 其他角色登录验证逻辑类似,此处省略
response.sendRedirect("error.jsp");
}
}
}
查看个人信息
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/employee/viewInfo")
public class EmployeeViewInfoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取当前登录员工的工号(假设从 session 中获取)
String jobId = (String) request.getSession().getAttribute("jobId");
// 调用 EmployeeDAO 查询员工信息并设置到 request 中,转发到查看信息页面
// 示例代码,实际需完善查询和转发逻辑
request.setAttribute("employee", new EmployeeDAO().getEmployeeByJobId(jobId));
request.getRequestDispatcher("employee_view_info.jsp").forward(request, response);
}
}
修改个人信息
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/employee/updateInfo")
public class EmployeeUpdateInfoServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取修改后的员工信息,调用 EmployeeDAO 更新信息
// 示例代码,需完善参数获取和更新逻辑,以及错误处理和返回页面逻辑
String jobId = request.getParameter("job_id");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String birthday = request.getParameter("birthday");
EmployeeDAO dao = new EmployeeDAO();
Employee employee = dao.getEmployeeByJobId(jobId);
if (employee!= null) {
employee.setName(name);
employee.setSex(sex);
employee.setBirthday(birthday);
dao.updateEmployee(employee);
request.setAttribute("message", "个人信息修改成功");
} else {
request.setAttribute("message", "员工不存在,修改失败");
}
request.getRequestDispatcher("employee_update_info_result.jsp").forward(request, response);
}
}
修改个人密码
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/employee/updateInfo")
public class EmployeeUpdateInfoServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取修改后的员工信息,调用 EmployeeDAO 更新信息
// 示例代码,需完善参数获取和更新逻辑,以及错误处理和返回页面逻辑
String jobId = request.getParameter("job_id");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String birthday = request.getParameter("birthday");
EmployeeDAO dao = new EmployeeDAO();
Employee employee = dao.getEmployeeByJobId(jobId);
if (employee!= null) {
employee.setName(name);
employee.setSex(sex);
employee.setBirthday(birthday);
dao.updateEmployee(employee);
request.setAttribute("message", "个人信息修改成功");
} else {
request.setAttribute("message", "员工不存在,修改失败");
}
request.getRequestDispatcher("employee_update_info_result.jsp").forward(request, response);
}
}
做到这里程序一直报错,没有找到错误原因

标签:preparedStatement,java,12.23,DB,department,2019,employee,import
From: https://www.cnblogs.com/bixi/p/18635783

相关文章

  • Java性能提升的其他技巧
    Java性能提升的其他技巧虚拟线程Java19引入的一种轻量级线程,即虚拟线程(VirtualThread),并在Java21中正式GA。虚拟线程是Java21引入的一个新特性,用于简化并发编程。它与传统的操作系统线程相比,具有显著的优势:轻量级:虚拟线程由JVM管理,而非操作系统,因此它们的内存占......
  • 别再夹灰了!这份Java架构六大专题面试宝典值得你好好刷一刷
    Java面试是一个老生常谈的问题。每年到了金三银四&金九银十这种跳槽黄金季就会有一大批程序员出来面试找工作。流程就是熟悉的网上开始找面试题,面试手册,面试宝典,一收藏就是一大把,看到什么都觉得Nice,看几眼之后就收藏夹吃灰,对面试其实起不到什么实际性帮助。但其实只要你不做收......
  • JAVA-Day 02:注释
    JAVA中的三种注释1.单行注释单行注释格式为"//语句",在语句前添加两个斜杠"//"即可,如下图所示;publicclassexegesispublicstaticvoidmain(String[]args){//输出一个"Hello,world!"System.out.print("Hello,World!");}注意:单行注释只能注释一条语句!2.多......
  • JAVA-PTA题目集总结3
    ​1.前言    经过这两次对家具强电电路模拟的迭代,我对JAVA编程语言有了更深入的理解,同时在程序开发设计环节也有了很大的进步,吸收了上次编程练习的教训后,我在本阶段的编程练习中也有针对性的进行了改进。        本次的JAVA练习内容丰富,包括各种数据结构的应用......
  • 免费送源码(计算机毕业设计原创定制):Java+CSS+springboot Springboot高校医务室管理系统
    摘 要科技进步的飞速发展引起人们日常生活的巨大变化,电子信息技术的飞速发展使得电子信息技术的各个领域的应用水平得到普及和应用。信息时代的到来已成为不可阻挡的时尚潮流,人类发展的历史正进入一个新时代。在现实运用中,应用软件的工作规则和开发步骤,采用java技术建设高校......
  • 免费送源码:Java+springboot+MySQL 房屋租赁系统小程序的设计与实现 计算机毕业设计原
    目 录摘要11绪论11.1选题意义11.2开发现状11.3springboot框架介绍11.4论文结构与章节安排12 房屋租赁系统小程序系统分析32.1可行性分析32.1.1技术可行性分析32.1.2经济可行性分析32.1.3法律可行性分析32.2系统功能分析32.2.1功能性分析......
  • 12.19 JAVA实战2019错题本系统(1)
    今天实战写一下建民老师发的2019年错题本系统。1.在IDE中创建一个Maven项目,项目的基本目录结构如下:src/main/java:用于存放Java源代码,包括Servlet、JavaBean等类。src/main/resources:放置配置文件,如数据库连接配置文件(.properties文件)等。src/main/webapp:Web相关资源......
  • Java 编程中 Bean、PO、POJO、VO、Entity、Model、DTO 术语全面解析对比
    术语描述特点用途BeanJava语言中可重用的组件,通常具有属性和对应的getter、setter方法等遵循JavaBean规范,具有一定的封装性和可访问性用于构建Java应用程序的各种组件,如在框架中作为配置信息的载体等PO持久化对象,通常与数据库中的表结构相对应与数据库表结构紧......
  • 12.20 java实战2019年错题本系统(2)
    今天继续2019年错题本系统的练习,昨天已经完成了除增删改查和页面设计的其他部分。1.新增请假申请Servlet(AddLeaveServlet)importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.h......
  • 12.16博客 备战java14
    今天学习增删改查中的修改功能,这部分是期末考试必须拿到的分数建立数据库连接。构建UPDATE语句的PreparedStatement对象,其中有两个占位符,第一个用于设置要更新的年龄值,第二个用于指定要修改的记录的ID(通过WHERE子句来限定条件)。执行executeUpdate方法进行修改操作,同样......