2、创建jdbc项目,实现数据库连接,并完成如下功能: 1)输入一个员工的信息,完成员工的添加。 2)完成如下查询: 2.1)查询所有员工信息; 2.2)输入姓名,查询员工信息; 3、创建jdbc项目,使用逻辑三层结构,把第2题的功能重新实现一遍;

时间: 2024-01-22 13:17:47 浏览: 26
1. 创建jdbc项目并实现数据库连接 首先,我们需要在项目中引入 JDBC 驱动程序,以便程序能够连接到数据库。这里我们以 MySQL 数据库为例,将 mysql-connector-java.jar 文件复制到项目的 lib 目录下,然后在项目的 Build Path 中添加该 jar 包。 接下来,我们创建一个名为 DBUtil 的 Java 类,用于封装数据库连接相关的代码。具体实现如下: ``` import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DBUtil { // 数据库连接信息 private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8"; private static final String USERNAME = "root"; private static final String PASSWORD = "123456"; // 获取数据库连接 public static Connection getConnection() { Connection conn = null; try { Class.forName(DRIVER); conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } // 关闭资源 public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs) { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } ``` 这个类中有两个方法,一个是获取数据库连接的方法,另一个是关闭资源的方法。我们在需要使用数据库连接时,调用 `getConnection()` 方法即可。 2. 实现员工信息的添加和查询 接下来,我们创建一个名为 Employee 的 Java 类,用于表示员工信息,具体实现如下: ``` public class Employee { private Integer id; private String name; private Integer age; private String department; public Employee() {} public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } } ``` 这个类中包含员工的 ID、姓名、年龄和所在部门等属性,以及对应的 getter 和 setter 方法。 接下来,我们创建一个名为 EmployeeDAO 的 Java 类,用于封装员工信息的添加和查询操作。具体实现如下: ``` import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class EmployeeDAO { // 添加员工信息 public void addEmployee(Employee emp) { Connection conn = null; PreparedStatement pstmt = null; try { conn = DBUtil.getConnection(); String sql = "INSERT INTO employee(name, age, department) VALUES (?, ?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, emp.getName()); pstmt.setInt(2, emp.getAge()); pstmt.setString(3, emp.getDepartment()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(conn, pstmt, null); } } // 查询所有员工信息 public List<Employee> getAllEmployees() { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List<Employee> employees = new ArrayList<Employee>(); try { conn = DBUtil.getConnection(); String sql = "SELECT * FROM employee"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { Employee emp = new Employee(); emp.setId(rs.getInt("id")); emp.setName(rs.getString("name")); emp.setAge(rs.getInt("age")); emp.setDepartment(rs.getString("department")); employees.add(emp); } } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(conn, pstmt, rs); } return employees; } // 根据姓名查询员工信息 public Employee getEmployeeByName(String name) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; Employee emp = null; try { conn = DBUtil.getConnection(); String sql = "SELECT * FROM employee WHERE name=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, name); rs = pstmt.executeQuery(); if (rs.next()) { emp = new Employee(); emp.setId(rs.getInt("id")); emp.setName(rs.getString("name")); emp.setAge(rs.getInt("age")); emp.setDepartment(rs.getString("department")); } } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(conn, pstmt, rs); } return emp; } } ``` 这个类中包含三个方法,一个是添加员工信息的方法,一个是查询所有员工信息的方法,另一个是根据姓名查询员工信息的方法。在这些方法中,我们使用了 JDBC API 来操作数据库。 3. 使用逻辑三层结构实现员工信息的添加和查询 在上面的实现中,我们直接在 DAO 类中操作数据库。为了更好地模块化程序,我们可以使用逻辑三层结构来重新实现功能。 首先,我们创建一个名为 EmployeeService 的 Java 类,用于封装业务逻辑。具体实现如下: ``` import java.util.List; public class EmployeeService { private EmployeeDAO dao = new EmployeeDAO(); // 添加员工信息 public void addEmployee(Employee emp) { dao.addEmployee(emp); } // 查询所有员工信息 public List<Employee> getAllEmployees() { return dao.getAllEmployees(); } // 根据姓名查询员工信息 public Employee getEmployeeByName(String name) { return dao.getEmployeeByName(name); } } ``` 这个类中包含三个方法,分别对应员工信息的添加、查询所有员工信息和根据姓名查询员工信息的操作。在这些方法中,我们直接调用 DAO 类中的方法。 接下来,我们创建一个名为 EmployeeController 的 Java 类,用于处理用户请求。具体实现如下: ``` import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/employee") public class EmployeeController extends HttpServlet { private EmployeeService service = new EmployeeService(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if (action != null && action.equals("addEmployee")) { addEmployee(request, response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if (action != null && action.equals("getAllEmployees")) { getAllEmployees(request, response); } else if (action != null && action.equals("getEmployeeByName")) { getEmployeeByName(request, response); } } // 添加员工信息 private void addEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); Integer age = Integer.parseInt(request.getParameter("age")); String department = request.getParameter("department"); Employee emp = new Employee(); emp.setName(name); emp.setAge(age); emp.setDepartment(department); service.addEmployee(emp); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>添加员工信息</title></head>"); out.println("<body>"); out.println("<h1>添加员工信息成功!</h1>"); out.println("</body>"); out.println("</html>"); } // 查询所有员工信息 private void getAllEmployees(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Employee> employees = service.getAllEmployees(); request.setAttribute("employees", employees); request.getRequestDispatcher("employeeList.jsp").forward(request, response); } // 根据姓名查询员工信息 private void getEmployeeByName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); Employee emp = service.getEmployeeByName(name); request.setAttribute("employee", emp); request.getRequestDispatcher("employeeDetail.jsp").forward(request, response); } } ``` 这个类中包含三个方法,分别对应员工信息的添加、查询所有员工信息和根据姓名查询员工信息的操作。在这些方法中,我们通过调用 Service 类中的方法来实现业务逻辑。 最后,我们创建两个 JSP 页面,一个名为 employeeList.jsp,用于显示所有员工信息,具体实现如下: ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>所有员工信息</title> </head> <body> <h1>所有员工信息</h1> <table border="1"> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>部门</th> </tr> <c:forEach var="emp" items="${employees}"> <tr> <td>${emp.id}</td> <td>${emp.name}</td> <td>${emp.age}</td> <td>${emp.department}</td> </tr> </c:forEach> </table> </body> </html> ``` 另一个名为 employeeDetail.jsp,用于显示根据姓名查询到的员工信息,具体实现如下: ``` <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>员工详细信息</title> </head> <body> <h1>员工详细信息</h1> <table border="1"> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> <th>部门</th> </tr> <c:if test="${employee != null}"> <tr> <td>${employee.id}</td> <td>${employee.name}</td> <td>${employee.age}</td> <td>${employee.department}</td> </tr> </c:if> </table> </body> </html> ``` 这两个 JSP 页面中使用了 JSTL 标签库来显示员工信息。 至此,我们完成了使用逻辑三层结构实现员工信息的添加和查询的任务。

相关推荐

最新推荐

recommend-type

javaee 实验报告 实验一 JSP+Servlet+Javabean+jdbc-基于MVC模式的数据库的应用

实验一 JSP+Servlet+Javabean+jdbc-基于MVC模式的数据库的应用 实验二 JSF+JPA实现用户注册 实验三 struts+spring+hibernate框架访问数据库的应用 实验四 使用WebService和EJBean访问数据库的应用
recommend-type

JDBC连接DB2数据库详解.doc--转载

关于DB2数据库的JDBC连接文章有很多,比较出名的有诸如“JDBC数据库连接大全”和“JSP的DB2连接数据库”,虽然都是很详细的资料,也都说解决了前人没有解决的问题,但还是有许多纰漏。我就这两天的经验给大家写一篇...
recommend-type

JAVA使用JDBC技术操作SqlServer数据库实例代码

本篇文章主要介绍了JAVA使用JDBC技术操作SqlServer数据库实例代码,具有一定的参考价值,有兴趣的可以了解一下。
recommend-type

EJB实验报告。实验一:使用Session Bean和JDBC技术完成登录和注册功能

实验一:使用Session Bean和JDBC技术完成登录和注册功能 实验二:使用Entity Bean替代JDBC完成登录和注册 实验三:在登录或注册成功之后,使用Message-Driven Bean对客户端发送消息 实验四:使用Servlet和JSP技术...
recommend-type

Java使用JDBC向MySQL数据库批次插入10W条数据(测试效率)

使用JDBC连接MySQL数据库进行数据插入的时候,特别是大批量数据连续插入(100000),如何提高效率呢?今天小编通过本教程给大家介绍下
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

hive中 的Metastore

Hive中的Metastore是一个关键的组件,它用于存储和管理Hive中的元数据。这些元数据包括表名、列名、表的数据类型、分区信息、表的存储位置等信息。Hive的查询和分析都需要Metastore来管理和访问这些元数据。 Metastore可以使用不同的后端存储来存储元数据,例如MySQL、PostgreSQL、Oracle等关系型数据库,或者Hadoop分布式文件系统中的HDFS。Metastore还提供了API,使得开发人员可以通过编程方式访问元数据。 Metastore的另一个重要功能是跟踪表的版本和历史。当用户对表进行更改时,Metastore会记录这些更改,并且可以让用户回滚到
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。