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

使用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条回答

      报告相同问题?

      相关推荐 更多相似问题

      问题事件

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

      悬赏问题

      • ¥15 postman测试正常,在代码运行报错
      • ¥15 关于#C语言#的问题,如何解决?
      • ¥20 Vs2017 Help Viewer2.3 问题
      • ¥35 基于嵌入式linux的日程管理软件
      • ¥50 如何将list字符串添加到CSV文件表头?
      • ¥15 关于#javascript#的问题:通过ajax实现的局部刷新 如何将项目打包
      • ¥15 海思uboot USB3.0无法识别
      • ¥15 无法调用库文件,自己可以找到,但编译时显示没有
      • ¥15 安装PyQt5的时候这里创建虚拟环境是哪里?具体是怎么的?能录个视频吗
      • ¥20 php程序设计题不会!求解答!