美文网首页
JAVA Web学习(15)___第10章 Java Web的数

JAVA Web学习(15)___第10章 Java Web的数

作者: 岁月静好浅笑安然 | 来源:发表于2019-08-28 14:41 被阅读0次

10.3.2 查询数据

10.3.3 修改数据

10.3.4 删除数据

ShowBook.jsp此页面包含查询、修改、删除

微信截图_20190828113259.png
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.hwp.bean.Book"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>


<title>查询、修改、删除</title>

    <link rel="stylesheet" type="text/css" href="styles.css">


</head>

<body>
    <table align="center" width="600" border="1">
        <tr>
            <td align="center" colspan="7">所有图书信息</td>
        </tr>
        <tr>
            <td align="center"><b>ID</b></td>
            <td align="center"><b>图书名称</b></td>
            <td align="center"><b>价格</b></td>
            <td align="center"><b>数量</b></td>
            <td align="center"><b>作者</b></td>
            <td align="center"><b>修改数量</b></td>
            <td align="center"><b>删除</b></td>
        </tr>
        <%
            List<Book> list = (List<Book>) request.getAttribute("list");
            if (list == null || list.size() < 1) {
            } else {
                for (int i = 0; i < list.size(); i++) {
                    Book _book = list.get(i);
        %>
        <!-- <tr/> <td/>是要写在循环里面的 -->
        <tr align="center">
            <td ><%=_book.getId()%></td>
            <td ><%=_book.getName()%></td>
            <td ><%=_book.getPrice()%></td>
            <td ><%=_book.getBookCount()%></td>
            <td ><%=_book.getAuthor()%></td>
            <td >
            <!-- 此处注意千万不要分号  /UpdateCountServlet 一定会报404 -->
            <form action="UpdateCountServlet" method="post" onsubmit="return check(this)">
            <input type="hidden" name="id" value="<%=_book.getId() %>"></input>
            <input type="text" name="bookCount" size="3"></input>
            <input type="submit" value="修改"></input>
            </form>
            </td>
            <td >
            <!-- 此处注意千万不要分号  /DeleteServlet 一定会报404 -->
            <form action="DeleteServlet" method="post" onsubmit="return check(this)">
            <input type="hidden" name="id" value="<%=_book.getId() %>"></input>
            <input type="submit" value="删除"></input>
            </form>
            </td>
        </tr>
        <%
            }
            }
        %>
    </table>
</body>
</html>

UpdateCountServlet.java修改bookCount数量

@WebServlet("/UpdateCountServlet")
public class UpdateCountServlet  extends HttpServlet{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doGet(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        int id=Integer.valueOf(req.getParameter("id"));
        int bookCount=Integer.valueOf(req.getParameter("bookCount"));

        try{
            Class.forName("com.mysql.jdbc.Driver");         //加载数据库驱动
            String password="hwp123456";                    //数据库密码
            String user="root";                             //数据库账号
            String url="jdbc:mysql://localhost:3306/book";  //数据库连接字符串
            Connection conn = DriverManager.getConnection(url, user, password);//创建Connection连接
            String sql="update book_info set bookCount=? where id=? ";  //更新SQL语句
            
            PreparedStatement ps= (PreparedStatement) conn.prepareStatement(sql); 获取PreparedStatement对象
            ps.setInt(1, bookCount);    //对sql语句中的参数1赋值
            ps.setInt(2, id);           //对sql语句中的参数2赋值
            ps.executeUpdate();         //执行更新操作
            ps.close();                 //关闭PreparedStatement
            conn.close();               //关闭 Connection
            
            
            
        }catch(Exception e){
            e.printStackTrace();
        }
        resp.sendRedirect("FindServlet"); //重定向到FindServlet
    }

}

DeleteServlet.java删除条目

@WebServlet("/DeleteServlet")
public class DeleteServlet extends HttpServlet {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doGet(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        int id=Integer.valueOf(req.getParameter("id"));    //获取图书ID

        try{
            Class.forName("com.mysql.jdbc.Driver");        //加载数据库驱动
            String password="hwp123456";                   //数据库密码
            String user="root";                            //数据库用户名
            String url="jdbc:mysql://localhost:3306/book"; //数据库连接字符串
            Connection conn = DriverManager.getConnection(url, user, password);//创建Connection连接
            String sql="delete from book_info  where id=? ";    //删除图书信息的SQL语句
            //String sql="select*from book_info";
            PreparedStatement ps= (PreparedStatement) conn.prepareStatement(sql);   //获取PreparedStatement对象
            ps.setInt(1, id);           //对sql语句中的第一个占位符赋值
            ps.executeUpdate();         //执行更新操作
            ps.close();                 //关闭 PreparedStatement
            conn.close();               //关闭 Connection
            
            
            
        }catch(Exception e){
            e.printStackTrace();
        }
        resp.sendRedirect("FindServlet");   //重定向到FindServlet 
    }

}

10.3.5 批处理

  • 1.创建数据库表 表结构(如图)

    微信截图_20190828143016.png
  • 2.创建Batch.java

public class Batch {
    
/**
 * 获取 Connection对象
 * @return
 */
    public Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //解决中文乱码
            String url = "jdbc:mysql://localhost:3306/book?characterEncoding=utf-8";
            String user = "root";
            String password = "hwp123456";
            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
        
            e.printStackTrace();
        }
        return conn;
    }
/**
 * 保存数据
 * @return
 */
    public int save() {
        int row = 0;
        Connection conn = getConnection();
        try {
            String sql = "insert into tb_studnet_batch(name,sex,age)values(?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            Random random = new Random();
            for (int i = 0; i < 10; i++) {
                ps.setString(1, "名字" + (i + 1));
                ps.setString(2, i % 2 == 0 ? "男" : "女");
                ps.setInt(3, random.nextInt(5) + 10);
                ps.addBatch();
            }
            int[] rows = ps.executeBatch();
            row = rows.length;
            ps.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
            
        }
        return row;
    }

    
}

PreparedStatement对象的批处理操作调用的是executeBatch()而不是executeUpdate()方法或者execute()方法

  • 3.创建 students_add.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<jsp:useBean id="batch" class="com.hwp.Batch"></jsp:useBean>
<%
int row=batch.save();
out.print("批量添加了"+row+"条数据");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>


<title>批量操作</title>


</head>

<body>
    This is my JSP page.
    <br>
</body>
</html>

相关文章

网友评论

      本文标题:JAVA Web学习(15)___第10章 Java Web的数

      本文链接:https://www.haomeiwen.com/subject/dznpectx.html