JavaWeb——操作数据库之JDBC查询和更新数据

JavaWeb——JDBC 操作数据库

四、JDBC 向 MySQL 数据库查询和更新数据

1、查询数据

  • 新建一个 JSP 页面,编辑如下代码:
    <%--
    Created by IntelliJ IDEA.
    User: 御承扬
    Date: 2019/12/2
    Time: 16:43
    To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ page import="java.util.List" %>
    <%@page import="com.lyq.bean.Book" %>
    <%@ page import="java.sql.*" %>
    <%@ page import="java.util.ArrayList" %>
    <html>
    <head>
        <title>图书信息查询结果页面</title>
        <style type="text/css">
            body {
                background: #d7c7e9;
                align-items: center;
                text-align: center;
            }
        </style>
    </head>
    <body>
    <table align="center" width="450" border="1" height="180" bordercolor="white" bgcolor="black" cellpadding="1"
           cellspacing="1">
        <tr bgcolor="white">
            <td align="center" colspan="5">
                <h2>所有图书信息</h2>
            </td>
        </tr>
        <tr align="center" bgcolor="#e1ffc1">
            <td><b>ID</b></td>
            <td><b>图书名称</b></td>
            <td><b>价格</b></td>
            <td><b>数量</b></td>
            <td><b>作者</b></td>
        </tr>
        <%
            // 获取图书信息集合
            //List<Book> list = (List<Book>) request.getAttribute("list");
            try {
                    Class.forName("com.mysql.jdbc.Driver");
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8";
                String username = "root";
                String password = "**********";
                Connection conn = null;
                Statement stmt =null;
                ResultSet rs = null;
                List<Book> list = new ArrayList<Book>();
                try {
                    conn = DriverManager.getConnection(url, username, password);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                if(conn != null){
                    try{
                        stmt = conn.createStatement();
                        String sql = "select * from tb_books;";
                        rs = stmt.executeQuery(sql);
    
                        while (rs.next()) {
                            Book book = new Book();
                            book.setId(rs.getInt("id"));
                            book.setName(rs.getString("name"));
                            book.setPrice(rs.getDouble("price"));
                            book.setBookCount(rs.getInt("bookCount"));
                            book.setAuthor(rs.getString("author"));
                            list.add(book);
                        }
                    }catch(SQLException e){
                            e.printStackTrace();
                            out.print("查询失败!");
                        }
                }
            // 判断集合是否有效
            if (list.size() < 1) {
                out.print("没有数据!");
            } else {
                // 遍历图书集合中的数据
                for (Book book : list) {
        %>
        <tr align="center" bgcolor="white">
            <td><%=book.getId()%>
            </td>
            <td><%=book.getName()%>
            </td>
            <td><%=book.getPrice()%>
            </td>
            <td><%=book.getBookCount()%>
            </td>
            <td><%=book.getAuthor()%>
            </td>
        </tr>
        <%
                }
                try {
                    rs.close();
                    stmt.close();
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
    
        }
        %>
        <tr bgcolor="white">
        <td align="center" colspan="5">
            <input type="button" value="添加图书信息" onclick="window.location.href='book.jsp'">
        </td>
    </table>
    </body>
    </html>
    
  • 效果如下:
    在这里插入图片描述

2、更新数据

  • 更新数据稍微麻烦点,首先新建两个 Servlet 。
  • 第一个 Servlet:
    //@Software: IntelliJ IDEA
    // @Project: JavaWebProject1
    //@File:${NAME}
    //@Date:2019/12/3
    // Author:御承扬
    //E-mail:[email protected]
    package com.lyq.ServletSet;
    import com.lyq.bean.Book;
    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.*;
    import java.util.ArrayList;
    import java.util.List;
    @WebServlet(name = "FindServlet", urlPatterns = "/FindServlet")
    public class FindServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8";
            String username = "root";
            String password = "*********";
            Connection conn = null;
            Statement stmt =null;
            ResultSet rs = null;
            List<Book> list = new ArrayList<>();
            try {
                conn = DriverManager.getConnection(url, username, password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if(conn != null){
                try{
                    stmt = conn.createStatement();
                    String sql = "select * from tb_books;";
                    rs = stmt.executeQuery(sql);
    
                    while (rs.next()) {
                        Book book = new Book();
                        book.setId(rs.getInt("id"));
                        book.setName(rs.getString("name"));
                        book.setPrice(rs.getDouble("price"));
                        book.setBookCount(rs.getInt("bookCount"));
                        book.setAuthor(rs.getString("author"));
                        list.add(book);
                    }
                    request.setAttribute("list", list);
                    rs.close();
                    stmt.close();
                    conn.close();
                }catch(SQLException e){
                    e.printStackTrace();
                }
            }
            request.getRequestDispatcher("/JDBCOption/bookUpdate.jsp").forward(request, response);
        }
    }
    
  • 第二个 Servlet
    //@Software: IntelliJ IDEA
    // @Project: JavaWebProject1
    //@File:${NAME}
    //@Date:2019/12/3
    // Author:御承扬
    //E-mail:[email protected]
    package com.lyq.ServletSet;
    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.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    @WebServlet(name = "UpdateServlet", urlPatterns = "/UpdateServlet")
    public class UpdateServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            int id = Integer.parseInt(request.getParameter("id"));
            int bookCount = Integer.parseInt(request.getParameter("bookCount"));
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8";
            String username = "root";
            String password = "**********";
            Connection conn = null;
            try {
                conn = DriverManager.getConnection(url, username, password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if(conn != null){
                String sql = "update tb_books set bookCount=? where id=?";
                try {
                    PreparedStatement ps = conn.prepareStatement(sql);
                    ps.setInt(2,id);
                    ps.setInt(1, bookCount);
                    ps.executeUpdate();
                    ps.close();
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                response.sendRedirect("FindServlet");
            }
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        }
    }
    
  • 在建立一个 JSP 页面,代码如下:
    <%--
    Created by IntelliJ IDEA.
    User: 御承扬
    Date: 2019/12/3
    Time: 14:47
    To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ page import="com.lyq.bean.Book"%>
    <%@ page import="java.sql.*" %>
    <%@ page import="java.util.ArrayList" %>
    <%@ page import="java.util.List" %>
    <html>
    <head>
        <title>修改图书信息</title>
        <style type="text/css">
            body{
                background: #d7c7e9;
                align-items: center;
                text-align: center;
            }
        </style>
        <script type="text/javascript">
            function check(form){
                with(form){
                    if(bookCount.value === ""){
                        alert("图书数量不能为空");
                        return false;
                    }
                    return true;
                }
            }
        </script>
    </head>
    <body>
    <table align="center" width="450" border="1" height="180" bordercolor="white" cellpadding="1"
           cellspacing="1">
        <tr bgcolor="white">
            <td align="center" colspan="6">
                <h2>所有图书信息</h2>
            </td>
        </tr>
        <tr align="center" bgcolor="#e1ffc1">
            <td><b>ID</b></td>
            <td><b>图书名称</b></td>
            <td><b>价格</b></td>
            <td><b>数量</b></td>
            <td><b>作者</b></td>
            <td><b>修改数量</b></td>
        </tr>
        <%
            List<Book> list = (List<Book>) request.getAttribute("list");
            if(list == null ||list.size() < 1){
                out.print("没有数据");
            }else{
                for(Book book:list){
    
    
        %>
            <tr align="center">
                <td><%=book.getId()%>
                </td>
                <td><%=book.getName()%>
                </td>
                <td><%=book.getPrice()%>
                </td>
                <td><%=book.getBookCount()%>
                </td>
                <td><%=book.getAuthor()%>
                </td>
                <td>
                    <form action="${pageContext.request.contextPath}/UpdateServlet" method="post" onsubmit="return check(this)">
                        <input type="hidden" name="id" value="<%=book.getId()%>">
                        <label>
                            <input type="text" name="bookCount" size="3">
                        </label>
                        <input type="submit" value="修改">
                    </form>
                </td>
            </tr>
        <%
                }
            }
        %>
        <tr bgcolor="white">
            <td align="center" colspan="6">
                <input type="button" value="添加图书信息" onclick="window.location.href='book.jsp'">
            </td>
    </table>
    </body>
    </html>
    
  • 运行效果如下:
    在这里插入图片描述
  • 对第三行的数量进行修改
    在这里插入图片描述
  • 点击修改
    在这里插入图片描述

上一篇

下一篇

发布了146 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42896653/article/details/103354396