WW933 2022-06-10 12:35 采纳率: 57.1%
浏览 88
已结题

使用servlet向数据库中添加数据

问题遇到的现象和发生背景

用java servlet向数据库中添加数据

问题相关代码,请勿粘贴截图
<%-- 
    Document   : insertform
    Created on : 2022-6-8, 22:49:46
    Author     : Wenny
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
         <div  style=" width: 400px;height: 500px; margin: 0 auto;">
            ${message}
        <form action="./productsaddServlet"  method="post">
            <table border="1">
                <tr>
                    <td>编号</td>
                    <td><input type="text" name="id"></td>
                </tr>
                <tr>
                     <td>商品名称</td>
                      <td><input type="text" name="pname"></td>
                </tr>
                <tr>
                    <td>品牌</td>
                     <td><input type="text" name="brand"></td>
                                   
                </tr>
                <tr>
                      <td>价格</td>   
                      <td><input type="text" name="price"></td>
                </tr>
                 <tr>
                      <td>库存</td>   
                      <td><input type="text" name="stock"></td>
                </tr>
                  <tr>
                      <td colspan="2" align="center"><input type="submit" value="添加"></td>
                </tr>
            </table>           
        </form>
            </div>
    </body>
</html>




/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package newpackage;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Wenny
 */
@WebServlet(name = "productsaddServlet", urlPatterns = {"/productsaddServlet"})
public class productsaddServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet productsaddServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet productsaddServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);  }
    @Override


    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
          request.setCharacterEncoding("utf8");
        Connection conn=null;
        PreparedStatement add=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
              conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/exercise5", "root", "123456");
              String name=request.getParameter("pname");
            int pid2=Integer. parseInt (request.getParameter("id"));
            float price=Float. parseFloat(request.getParameter("price"));
            String brand=request.getParameter("brand");
            int stock=Integer. parseInt(request.getParameter("stock"));
             String sql2="insert into products(id,p_name,brand,price,stock) values("+pid2+","
                + "'"+name+"','"+brand+"',"+price+ ","+stock+")";
            add=conn.prepareStatement(sql2);
              int num=add.executeUpdate();
                 if(num>0)
                 {
                     request.setAttribute("message","添加成功");
                     request.getRequestDispatcher("/insertform.jsp").forward(request, response);
                 }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(productsaddServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(productsaddServlet.class.getName()).log(Level.SEVERE, null, ex);
        }finally
        {
                try {
                         if(add!=null)
                         {
                              add.close();
                         }
                           if(conn!=null)
            {
                conn.close();
            }
                          } catch (SQLException ex) {
                              Logger.getLogger(productsaddServlet.class.getName()).log(Level.SEVERE, null, ex);
                          }
            }     
    }
}
 
运行结果及报错内容

img

img

img

我的解答思路和尝试过的方法

一片空白连添加成功都没有,只知道那个有一个为空但不知道为什么

我想要达到的结果
  • 写回答

3条回答 默认 最新

查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 6月20日
  • 已采纳回答 6月12日
  • 创建了问题 6月10日

悬赏问题

  • ¥15 请问不小心下载到了钓鱼软件怎么办?
  • ¥15 求国博抢票 求国博抢票 有的私
  • ¥50 swiftui @query 报错
  • ¥50 怎么解决刷卡或扫码后,点击软件输入框,win10屏幕键盘不会自动弹出的问题
  • ¥15 如何使用arcgispro的训练深度模型,发现water和nowater精度为0?(相关搜索:深度学习)
  • ¥20 matlab作业不太懂呀有问题能给个代码吗
  • ¥15 自制电路图为何无法驱动ESP01S?
  • ¥15 前端加access数据库
  • ¥15 ARCGIS 多值提取到点 ERROR 999999
  • ¥15 mysql异常断电, [MY-011971] [InnoDB]