From f82dcf5a098a8b54d57375ccb962b3b6c05e469a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=AD=E5=AE=87=E9=91=AB?= <2366023603@qq.com> Date: Sun, 28 May 2023 22:29:43 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../\344\275\234\344\270\232.md" | 378 ++++++++++++++++-- 1 file changed, 354 insertions(+), 24 deletions(-) diff --git "a/06 \351\203\255\345\256\207\351\221\253/\344\275\234\344\270\232.md" "b/06 \351\203\255\345\256\207\351\221\253/\344\275\234\344\270\232.md" index ce71e1c..a193b86 100644 --- "a/06 \351\203\255\345\256\207\351\221\253/\344\275\234\344\270\232.md" +++ "b/06 \351\203\255\345\256\207\351\221\253/\344\275\234\344\270\232.md" @@ -1,51 +1,381 @@ ```java +package Util; + import java.sql.*; -import java.util.ArrayList; -import java.util.List; -public class DBUtil { - // 假设数据库连接信息已配置好 +public class JDBCUtil { + private static final String url = "jdbc:mysql://localhost:3306/student_db?useSSL=false&useUnicode=true&characterEncoding=utf8"; + private static final String username = "root"; + private static final String password = ""; + //注册驱动的方法 + //用静态代码块,注册驱动,{}表示代码块,static表示静态的,最先执行 + static { + try { + Class.forName("com.mysql.jdbc.Driver"); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + //获取连接对象的方法 + public static Connection getConn() throws SQLException { + Connection conn = DriverManager.getConnection(url, username, password); + return conn; + } + + /** + * 通用的query + * @param sql 接收的SQL语句 + * @return 将查询的结果集返回给调用者 + */ + public static ResultSet query(String sql,String ...keys) throws SQLException { + Connection conn = getConn(); + PreparedStatement pst = conn.prepareStatement(sql); + for (int i = 0; i < keys.length; i++) { + pst.setString(i+1,keys[i]); + } + ResultSet rst = pst.executeQuery(); + return rst; + + } + - public static List getStudents() { - List students = new ArrayList<>(); - try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "username", "password"); - Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT id, name, age FROM students")) { + //通用的update + public static int update(String sql,String ...keys) throws SQLException { + Connection conn = getConn(); + PreparedStatement pst = conn.prepareStatement(sql); + for (int i = 0; i < keys.length; i++) { + pst.setString(i+1,keys[i]); + } + int i = pst.executeUpdate(); + return i; - while (rs.next()) { - int id = rs.getInt("id"); - String name = rs.getString("name"); - int age = rs.getInt("age"); + } - Student student = new Student(id, name, age); - students.add(student); + //通用的释放资源的方法 + public static void close(Connection conn,PreparedStatement pst,ResultSet rst){ + try { + if (rst!=null){ + rst.close(); + } + if (pst!=null){ + rst.close(); + } + if (conn!=null){ + rst.close(); } } catch (SQLException e) { - e.printStackTrace(); + throw new RuntimeException(e); } - - return students; } } + ``` ```java +//学生类 +package been; + public class Student { private int id; private String name; - private int age; + private String sex; + + public Student() { + } + + public Student(int id, String name, String sex) { - public Student(int id, String name, int age) { this.id = id; this.name = name; - this.age = age; + this.sex = sex; } - // Getters and setters + public int getId() { + return id; + } - // 省略其他方法 + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSex() { + return sex; + } + + public void setSex(String sex) { + this.sex = sex; + } + + @Override + public String toString() { + return "Student{" + + "id=" + id + + ", name='" + name + '\'' + + ", sex='" + sex + '\'' + + '}'; + } +} + +``` + +```java +//修改学生 信息 +package servlet; + +import Util.JDBCUtil; +import been.Student; + +import javax.servlet.*; +import javax.servlet.http.*; +import javax.servlet.annotation.*; +import java.io.IOException; +import java.sql.ResultSet; +import java.sql.SQLException; + +@WebServlet("/updateById") +public class updateById extends HttpServlet { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + //根据ID获取对应的学生信息 + //写servlet要写请求和响应的编码 + request.setCharacterEncoding("utf-8"); + response.setContentType("text/html;charset=utf-8"); + //这个servlet要根据ID去数据库删除对应的学生信息 + String id = request.getParameter("id"); + //将得到的ID注入到sql语句 + String sql = "select * from student where id =?"; + try { + ResultSet rs = JDBCUtil.query(sql, id); + //此处得到一个学生的信息,不直接响应,而是封装成一个学生对象,将他转发给一个jsp,让他去处理 + rs.next();//这里不写which循环是因为我们的ID是唯一的,一个ID只有一个学生对象 + int id2 = rs.getInt("id"); + String name = rs.getString("name"); + String sex = rs.getString("sex"); + Student stu = new Student(id2, name, sex); + + //将stu对象,添加到request,并转发给负责表单的jsp + request.setAttribute("student",stu); + request.getRequestDispatcher("/edit.jsp").forward(request,response); + + + + } catch (SQLException e) { + throw new RuntimeException(e); + } + + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } } + ``` -````java +```java +//删除学生信息 +package servlet; + +import Util.JDBCUtil; + +import javax.servlet.*; +import javax.servlet.http.*; +import javax.servlet.annotation.*; +import java.io.IOException; +import java.sql.SQLException; + +@WebServlet("/deleteById") +public class deleteById extends HttpServlet { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + //写servlet要写请求和响应的编码 + request.setCharacterEncoding("utf-8"); + response.setContentType("text/html;charset=utf-8"); + //这个servlet要根据ID去数据库删除对应的学生信息 + String id = request.getParameter("id"); + //将得到的ID注入到sql语句 + String sql = "delete from student where id =?"; + try { + int i = JDBCUtil.update(sql, id); + if (i>0){ + response.getWriter().write(""); + //成功之后能不能自动调回列表 + //请求有请求转发,响应有重定向 +// response.sendRedirect("/index.jsp"); + + }else{ + response.getWriter().write("删除失败"); + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + } +} + +``` + +```java +//saveUpdate类 +package servlet; + +import Util.JDBCUtil; + +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; +import java.sql.SQLException; + +@WebServlet("/saveUpdate") +public class saveUpdate extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + doPost(req,resp); + } + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + + //接收表单信息,将信息保存到数据库 + //写servlet要写请求和响应的编码 + req.setCharacterEncoding("utf-8"); + resp.setContentType("text/html;charset=utf-8"); + + + String id = req.getParameter("id"); + String name = req.getParameter("name"); + String sex = req.getParameter("sex"); + + String sql = "update student set name=?,sex=? where id=?"; + int i = 0; + try { + i = JDBCUtil.update(sql, name, sex,id); + } catch (SQLException e) { + throw new RuntimeException(e); + } + if (i>0){ + resp.getWriter().write(""); + //成功之后能不能自动调回列表 + //请求有请求转发,响应有重定向 +// response.sendRedirect("/index.jsp"); + + }else{ + resp.getWriter().write("修改失败"); + } + + } +} + +``` + +```jsp +//index.jsp +<%@ page import="Util.JDBCUtil" %> +<%@ page import="java.sql.ResultSet" %><%-- + Created by IntelliJ IDEA. + User: Administrator + Date: 2023-05-27 + Time: 15:57 + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + 学生列表 + + + +<%-- 使用表格显示学生身份信息--%> + + + <% + String sql ="select * from student"; + ResultSet rs = JDBCUtil.query(sql); + while (rs.next()){ + int id = rs.getInt("id"); + String name = rs.getString("name"); + String sex = rs.getString("sex"); + //响应给浏览器的 + // response.getWriter().write(id); + // response.getWriter().write(name); + // response.getWriter().write(sex); + // response.getWriter().write("
"); + %> + + + + + + + + <% + } + %> + + + <%-- 具体每个学生的信息,是从数据库里 循环遍历出来的--%> + <%-- jsp中,java代码和html是可以互相嵌套的--%> + +
编号姓名性别操作
<%=id%><%=name%><%=sex%>修改 删除
+ + + + +``` + +```jsp +//edit.jsp +<%@ page import="been.Student" %> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + 修改学生信息 + + +<% +//从request取出来的学生对象 + Student student = (Student) request.getAttribute("student"); + + //在jsp中有一个标签< %=直接写变量 % > + +%> +<%--<%=student.getId()%>--%> +<%--<%=student.getName()%>--%> +<%--<%=student.getSex()%>--%> + +<%--写表单注意两点:1,谁来接收我们表单的数据 2,以什么方式提交get post--%> + + + 姓名:
+ 性别:
+
+ +
+ + + + + +``` -- Gitee