zoukankan      html  css  js  c++  java
  • JDBC之修改数据

    文件分布图:

    在MySQL中设置表格:

    Books:

    package com.caiduping.entity;
    
    public class Books {
        private int id;
        // 图书名称
        private String name;
        // 价格
        private double price;
        // 数量
        private int bookCount;
        // 作者
        private String author;
        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 double getPrice() {
            return price;
        }
        public void setPrice(double price) {
            this.price = price;
        }
        public int getBookCount() {
            return bookCount;
        }
        public void setBookCount(int bookCount) {
            this.bookCount = bookCount;
        }
        public String getAuthor() {
            return author;
        }
        public void setAuthor(String author) {
            this.author = author;
        }
    }

    bookdao:

    package com.caiduping.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.Statement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.List;
    import java.util.ArrayList;
    import com.caiduping.dao.dataconn;
    import com.caiduping.entity.Books;
    
    public class bookdao {
        public int addBooks(Books b) throws ClassNotFoundException,SQLException{
            dataconn c=new dataconn();
            Connection conn=c.openconn();
            String sql = "insert into tb_books(name,price,bookCount,author) values(?,?,?,?)";
            // 获取PreparedStatement
             PreparedStatement ps = conn.prepareStatement(sql);
            // 对SQL语句中的第1个参数赋值
             ps.setString(1, b.getName());
             System.out.println("name:"+b.getName());
            // 对SQL语句中的第2个参数赋值
              ps.setDouble(2, b.getPrice());
              // 对SQL语句中的第3个参数赋值
              ps.setInt(3,b.getBookCount());
              // 对SQL语句中的第4个参数赋值
              ps.setString(4, b.getAuthor());
              // 执行更新操作,返回所影响的行数
              int row = ps.executeUpdate();
              // 判断是否更新成功
              conn.close();
              return row;      
        }
        public List<Books> Listbook() throws ClassNotFoundException, SQLException{
            List<Books> b=new ArrayList<Books>();
             dataconn c=new dataconn();
             Connection conn=c.openconn();
             Statement st=conn.createStatement();
              ResultSet rs=st.executeQuery("select * from tb_books");  //利用st执行语句,结果防到结果集.
              while(rs.next())
              {Books b1=new Books();
              b1.setId(rs.getInt("id"));
              b1.setName(rs.getString("name"));
              b1.setPrice(rs.getDouble("price"));
              b1.setBookCount(rs.getInt("bookCount"));
              b1.setAuthor(rs.getString("author"));
              b.add(b1);
              }
              rs.close();
              st.close();
              conn.close();
              return b;
        }
         public List<Books> Listbook(String a) throws ClassNotFoundException, SQLException  //查询书籍名称含有a串的书籍
          {List<Books> b=new ArrayList<Books>();
          dataconn c=new dataconn();
          Connection conn=c.openconn();
          Statement st=conn.createStatement();
          ResultSet rs=st.executeQuery("select * from tb_books where name like '%'+" + a + "+'%'");  //利用st执行语句,结果防到结果集.
          while(rs.next())
          {Books b1=new Books();
          b1.setId(rs.getInt("id"));
          b1.setName(rs.getString("name"));
          b1.setPrice(rs.getDouble("price"));
          b1.setBookCount(rs.getInt("bookCount"));
          b1.setAuthor(rs.getString("author"));
          b.add(b1);
          }
          rs.close();
          st.close();
          conn.close();
          return b;
          
          }
         public Books Listbook(int a) throws ClassNotFoundException, SQLException //参数a为书籍编号
          {Books b1=new Books();
          dataconn c=new dataconn();
          Connection conn=c.openconn();
          Statement st=conn.createStatement();
          ResultSet rs=st.executeQuery("select * from tb_books where id=" + a);  //利用st执行语句,结果防到结果集.
          if(rs.next())
          {
          b1.setId(rs.getInt("id"));
          b1.setName(rs.getString("name"));
          b1.setPrice(rs.getDouble("price"));
          b1.setBookCount(rs.getInt("bookCount"));
          b1.setAuthor(rs.getString("author"));
         
          }
          rs.close();
          st.close();
          conn.close();
          return b1;
    }
         public int modiBooks(Books b) throws SQLException, ClassNotFoundException
          {int a=0;
          dataconn c=new dataconn();
          Connection conn=c.openconn();
          String sql="update tb_books set name=?,price=?,bookCount=?,author=? where id=?";
          PreparedStatement ps=conn.prepareStatement(sql);
          ps.setString(1,b.getName());
          ps.setDouble(2, b.getPrice());
          ps.setInt(3,b.getBookCount());
          ps.setString(4, b.getAuthor());
          ps.setInt(5,b.getId());
          a=ps.executeUpdate();
          ps.close();
          conn.close();
           
          return a;
          }}

    dataconn:

    package com.caiduping.dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class dataconn {
        public Connection openconn()throws ClassNotFoundException,SQLException {
            // TODO Auto-generated method stub
            Connection conn=null;
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_database10","user2","123456");
            return conn;
        }
    }

    Booklist:

    package com.caiduping.servlet;
    
    import java.io.IOException;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.caiduping.dao.bookdao;
    import com.caiduping.entity.Books;
    
    public class Booklist extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public Booklist() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
                bookdao b=new bookdao();
                List<Books> b1=new ArrayList<Books>();
                try{
                    try {
                        b1=b.Listbook();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }catch(ClassNotFoundException e){
                    e.printStackTrace();
                }
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response);
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
        }
    
    }

    modibooks1:

    package com.caiduping.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.SQLException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.caiduping.dao.bookdao;
    import com.caiduping.entity.Books;
    
    public class modibooks1 extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public modibooks1() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            int a=Integer.parseInt(request.getParameter("ID"));
            bookdao b=new bookdao();
            Books b1=new Books();
            try{
                try {
                    b1=b.Listbook(a);
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }catch(ClassNotFoundException e){
                e.printStackTrace();
            }
            request.setAttribute("book", b1);
            request.getRequestDispatcher("modi1.jsp").forward(request, response);
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            doGet(request, response);
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
        }
    
    }

    modibooks2:

    package com.caiduping.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.SQLException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.caiduping.dao.bookdao;
    import com.caiduping.entity.Books;
    
    public class modibooks2 extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public modibooks2() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
                Books b=new Books();
                b.setId(Integer.parseInt(request.getParameter("id").toString()));
                b.setName(request.getParameter("name"));
                b.setPrice(Double.parseDouble(request.getParameter("price").toString()));
                b.setAuthor(request.getParameter("author"));
                bookdao b1=new bookdao();
                int n=0;
                try{
                    try {
                        n=b1.modiBooks(b);
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }catch(SQLException e){
                    e.printStackTrace();
                }
                request.getRequestDispatcher("b").forward(request, response);
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response);
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
        }
    
    }

    book_list.jsp:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ page import="com.caiduping.entity.Books" %>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'book_list.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
       <table width="600" border="0" align="center">
      <tr>
        <td>编号</td>
        <td>名称</td>
        <td>单价</td>
        <td>数量</td>
        <td>作者</td><td>操作</td>
      </tr>
      <% 
      List<Books> list=(List<Books>)request.getAttribute("list"); 
      if(list==null||list.size()<1){
      out.print("没有数据!");
      }else{
      %>
      <%for(Books b:list){ %>
    <tr>
        <td><%=b.getId() %></td>
        <td><%=b.getName() %></td>
        <td><%=b.getPrice() %></td>
        <td><%=b.getBookCount() %></td>
        <td><%=b.getAuthor() %></td>
        <td><a href="modi?ID=%=b.getId() %>">修改</a></td>
      </tr>
      <% 
      }
      } %>
      </table>
      </body>
    </html>

    modi1.jsp:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ page  import="com.caiduping.entity.Books" %>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'modi1.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
       <%
      Books b=(Books)request.getAttribute("books"); %>
        <form id="form1" name="form1" method="post" action="modi2">
        <input type="hidden" name="id" value="<%=b.getId()%>" />
      <table width="400" border="0" align="center">
        <tr>
          <td colspan="2"><div align="center" class="STYLE1">书籍修改</div></td>
        </tr>
        
        <tr>
          <td>书名</td>
          <td><label>
            <input name="name" type="text" id="name" value="<%=b.getName()%>"/>
          </label></td>
        </tr>
        <tr>
          <td>单价</td>
          <td><label>
            <input name="price" type="text" id="price" value="<%=b.getPrice()%>"/>
          </label></td>
        </tr>
        <tr>
          <td>数量</td>
          <td><label>
            <input name="bookCount" type="text" id="bookCount" value="<%=b.getBookCount()%>"/>
          </label></td>
        </tr>
        <tr>
          <td>作者</td>
          <td><label>
            <input name="author" type="text" id="author" value="<%=b.getAuthor()%>"/>
          </label></td>
        </tr>
        <tr>
          <td colspan="2"><label>
            <div align="center">
              <input type="submit" name="Submit" value="修改" />
              </div>
          </label></td>
        </tr>
      </table>
    </form>
      </body>
    </html>
    不努力,还要青春干什么?
  • 相关阅读:
    Sudoku POJ 2676 [dfs]
    a>b和(*a).b
    lowbit()操作
    Anniversary party HDU 1520树形dp
    Lifting the Stone HDU 1115 求多边形的重心
    Boolean Expressions POJ 2106 【递归】
    Shaolin HDU 4585 STL map||Treap树
    取石子游戏 HDU 1527 威佐夫游戏
    A Simple Problem with Integers POJ 3468 区间修改线段树lazy—tag大法
    社会性网络软件SNS 帮助你认识比尔盖茨 java程序员
  • 原文地址:https://www.cnblogs.com/caidupingblogs/p/5318493.html
Copyright © 2011-2022 走看看