实现简单的数据库查询(不完整)

文章目录

  • 实现简单的数据库查询
      • JS要点:
          • 直接量(常量) :也称为“字面量”,就是看见什么,它就是什么。
          • 变量:(全用var定义)例:var a=100; var b="abc";
          • DOM介绍:
    • 1.创建Project (Module)
    • 2.创建lib文件
    • 3.建立静态资源包(static),放入所需要的静态资源
    • 写代码:
        • 1.建立pojo包,放入Student类:
        • 2.为了方便连接,将部分JDBC操作封装为JDBCUtil类:
        • 3.index.jsp引用layui样式(只使用学生管理部分)
        • 3.重写service方法,建立服务器(tomcat)将我们的代码以tomcat执行共享给浏览器。
        • 4.编写student_list.jsp

实现简单的数据库查询

JS要点:

  • JS:解释型语言。(由浏览器解释执行代码,不进行预编译。)
  • JS不区分单引号和双引号。
  • 直接嵌入HTML页面。
直接量(常量) :也称为“字面量”,就是看见什么,它就是什么。
  • 例如:alert(886)和alert(“886”)执行结果一样;//886是数字所以不需要加引号,"886"是字符串。
    实现简单的数据库查询(不完整)_第1张图片
变量:(全用var定义)例:var a=100; var b=“abc”;

变量名区分大小写,允许包含字母、数字、美元符号($)和下划线,但第一个字符不允许是数字,不允许包含空格和其他标点符号。

DOM介绍:

dom技术在JS里面作用:JS语言和Html/Xml标签之间沟通的一个桥梁。

为了方便javascript语言通过dom操作html比较方便,
把html标签的内容划分为各种节点:

  • 文档节点(document)
  • 元素节点 也叫标签 getElementsByTagName
  • 文本节点
  • 属性节点 type=”text” name=”username”
  • 注释节点

documnet:是页面中的内置对象,内置对象简单理解就是已经new好的一个对象,对象的名字就叫document。

  • 元素节点的获取:
    document.getElementById( id属性值);
  • document.getElementsByTagName(“标签名”);

关系运算符:

  • 全等:===
  • 不全等:!==

大小写转换

  • str.toLowerCase();
  • str.toUpperCase();

查询指定字符串出现索引

  • str.indexOf(findstr, index);
  • str.indexOf(findstr)
  • str.indexOf(findstr,index)
  • str.lastIndexOf(findstr, index);

  • split() 方法用于把一个字符串分割成字符串数组。

  • innerText 直接当成一个字符串展示;innerHtml 将内容当成html来解析

JSP的脚本:(脚本就是一段代码)

  • 语法:<%java代码 %>
  • 作用: 执行java代码

JSP表达式:

  • 语法:<%=变量或表达式%>
  • 作用: 向浏览器输出变量的值或表达式计算的结果

1.创建Project (Module)

创建完之后:
实现简单的数据库查询(不完整)_第2张图片

实现简单的数据库查询(不完整)_第3张图片

2.创建lib文件

实现简单的数据库查询(不完整)_第4张图片

如图:放入mysql驱动
实现简单的数据库查询(不完整)_第5张图片

3.建立静态资源包(static),放入所需要的静态资源

实现简单的数据库查询(不完整)_第6张图片
文件放下方,自取:

链接:https://pan.baidu.com/s/1v6W11ZOcYOtjwf6f_gZN0g
提取码:call

写代码:

1.建立pojo包,放入Student类:

package com.situ.web.pojo;

public class Student {
    private Integer id;
    private String name;
    private Integer age;
    private String gender;

    public Student(Integer id, String name, Integer age, String gender) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    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 getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
    }
}

2.为了方便连接,将部分JDBC操作封装为JDBCUtil类:

package com.situ.web.util;

import java.sql.*;

public class JDBCUtil {
 
    private final static String URL = "jdbc:mysql://localhost:3306/java2207?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private final static String USER = "root";
    private final static String PASSWORD = "root";
    
    //私有构造器防止被实例化
    private JDBCUtil() {
    }

    //加载驱动(static在类加载时执行一次)
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //建立连接
    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(URL,USER,PASSWORD);
        return connection;
    }
    //封装close方法,按照先建立的后关闭原则(与栈类似,创建顺序为connection,preparedStatement,resultSet,所以关闭时顺序如下)
    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

3.index.jsp引用layui样式(只使用学生管理部分)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>



  主页
  







3.重写service方法,建立服务器(tomcat)将我们的代码以tomcat执行共享给浏览器。

什么是Servlet?

servlet是java编写的服务器端的程序,运行在web服务器中
作用:

  • 接收用户端发来的请求
  • 调用其他java程序来处理请求 将处理结果,返回到服务器中
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //request请求编码统一。
        req.setCharacterEncoding("utf-8");
        
        String method = req.getParameter("method");
        if(method == null || method.equals("")){
            method = "selectAll";
        }
        switch(method){
            case "selectAll":
                selectAll(req,resp);
                break;
            case "deleteById":
                delete(req,resp);
                break;
            case "add":
                add(req,resp);
                break;
            case "update":
                update(req,resp);
                break;
            case "getStudentUpdatePage":
                getStudentById(req,resp);
                break;
        }

    }

    private void getStudentById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Student student = null;
        List<Student> list = new ArrayList<>();
        try {
            connection = JDBCUtil.getConnection();
            String sql = "select name,age,gender from student where id=?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,Integer.parseInt(id));
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                student = new Student(Integer.parseInt(id),name,age,gender);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtil.close(connection,preparedStatement,resultSet);
        }
        req.setAttribute("student",student);
        req.getRequestDispatcher("student_update.jsp").forward(req,resp);
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("StudentServlet.update");
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        Integer id = Integer.parseInt(req.getParameter("id"));
        String name = req.getParameter("name");
        Integer age = Integer.parseInt(req.getParameter("age"));
        String gender = req.getParameter("gender");
        try {
            connection = JDBCUtil.getConnection();
            String sql = "update student set name=?,age=?,gender=? where id=?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,name);
            preparedStatement.setInt(2,age);
            preparedStatement.setString(3,gender);
            preparedStatement.setInt(4,id);
            System.out.println(preparedStatement);
            int count = preparedStatement.executeUpdate();
            System.out.println(count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtil.close(connection,preparedStatement,null);
        }
        resp.sendRedirect(req.getContextPath() + "/student?method=selectAll");
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "insert into student(name,age,gender) values (?,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,name);
            preparedStatement.setInt(2, Integer.parseInt(age));
            preparedStatement.setString(3,gender);
            System.out.println(preparedStatement);
            int count = preparedStatement.executeUpdate();
            System.out.println(count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtil.close(connection,preparedStatement,null);
        }
        resp.sendRedirect(req.getContextPath() + "/student?method=selectAll");
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "delete from student where id=?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,Integer.parseInt(id));
            System.out.println(preparedStatement);
            int count = preparedStatement.executeUpdate();
            System.out.println(count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtil.close(connection,preparedStatement,null);
        }
        //重定向
        resp.sendRedirect(req.getContextPath() + "/student");
    }

    private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<Student> list = new ArrayList<>();
        try {
            connection = JDBCUtil.getConnection();
            String sql = "select id,name,age,gender from student";
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                Student student = new Student(id,name,age,gender);
                list.add(student);
            }
            for (Student student : list) {
                System.out.println(student);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtil.close(connection,preparedStatement,resultSet);
        }
        resp.setContentType("text/html;charset=utf-8");
        req.setAttribute("list",list);
        req.getRequestDispatcher("student_list.jsp").forward(req,resp);
    }
}

4.编写student_list.jsp

JSP:
Servlet的作用:用于java语言开发动态资源的技术!!
JSP的作用:用java语言 + html语言,开发动态资源的技术!!
JSP就是servlet!!!

JSP的脚本:(脚本就是一段代码)
语法:<%java代码 %>
作用: 执行java代码

JSP表达式:
语法:<%=变量或表达式%>
作用: 向浏览器输出变量的值或表达式计算的结果

%@ page import="java.util.List" %>
<%@ page import="com.situ.web.pojo.Student" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="static/bootstrap-3.4.1-dist/css/bootstrap.css"/>
</head>
<body>
${list}
<%
    List<Student> list = (List<Student>) request.getAttribute("list");
%>
<table class="table table-striped table-bordered table-hover table-condensed">
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
    </tr>
    <%
        for (Student student:list) {
    %>
        <tr>
            <td><%=student.getId()%></td>
            <td><%=student.getName()%></td>
            <td><%=student.getAge()%></td>
            <td><%=student.getGender()%></td>
            <td><a href="">删除</a></td>
        </tr>
    <%
        }
    %>

</table>
</body>
</html>

你可能感兴趣的:(java,Mysql,javascript,数据库,java)