【问题标题】:Inserting Data into the MySQL Database将数据插入 MySQL 数据库
【发布时间】:2023-04-10 05:29:02
【问题描述】:

我有如下的 html 表单。我想将数据添加到数据库表 itemspoinfo。我想按如下方式完成该功能;

  • 如果给出的第一个药物名称和数量将其添加到数据库中。
  • 如果给出的前 2 个药物名称和数量将其添加到数据库中。 (作为 2 个单独的记录以及 POno 和 Date)

  • 因为这最多 5 条记录必须能够记录到数据库中

我找不到解决方案,请帮助我。

到目前为止我做了什么;

   <%
    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);

    if(request.getParameter("send")!=null){
        String scom=request.getParameter("scompany");
        String porderno=request.getParameter("pono");
        String bdate=request.getParameter("date");

        String drug1=request.getParameter("d1");
        String qty1=request.getParameter("q1");
        String drug2=request.getParameter("d2");
        String qty2=request.getParameter("q2");
        String drug3=request.getParameter("d3");
        String qty3=request.getParameter("q3");
        String drug4=request.getParameter("d4");
        String qty4=request.getParameter("q4");
        String drug5=request.getParameter("d5");
        String qty5=request.getParameter("q5");


        //getting todaydate
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());

        String sql = "INSERT INTO purchaseorderinfo SET Supplier ='"+scom+"', PONo='"+porderno+"', ExpectedDate='"+bdate+"', PODate='"+timestamp+"' ";
        pst=conn.prepareStatement(sql);



        if((scom!=null && scom.length()>0)
            && (porderno!=null && porderno.length()>0)
            && (bdate!=null && bdate.length()>0)
            && (drug1!=null && drug1.length()>0)
            && (qty1!=null && qty1.length()>0)){


            pst.execute();

            String sql2="INSERT INTO itemspoinfo SET PODate=?, PONo=?, ItemName=?, Qty=?,";
            pst2=conn.prepareStatement(sql2);
            pst2.setTimestamp(1, timestamp);
            pst2.setString(2, porderno);



          %>
          <script language="javascript">
                alert("Sucessfuly Sent to "+scom);
          </script>
          <%    
        }
    }
%>

【问题讨论】:

  • 不要在jsp页面中使用java代码
  • 您使用的是update 语句还是insert 语句?
  • 您可能想了解Hibernate(ORM)
  • 我同意@SuhailGupta。请为此任务使用一些 ORM(可能是 Hibernate)。

标签: java mysql jsp


【解决方案1】:

您可以使用addBatch() 和executeBatch()。

试试下面的代码:

String sql2="INSERT INTO itemspoinfo (PODate, PONo, ItemName,Qty) VALUES(?,?,?,?)";
        pst2=conn.prepareStatement(sql2);
        // to check drugs details are added or not.
        int noofdrugs = 0;
        if (drug1!=null && drug1.length()>0)
            && (qty1!=null && qty1.length()>0)) {
            pst2.setTimestamp(1, timestamp);
            pst2.setString(2, porderno);
            pst2.setString(3, drug1);
            pst2.setInt(4, Integer.parseInt(qty1));
            pst2.addBatch();

            noofdrugs++;
        }

        if (drug2!=null && drug2.length()>0)
            && (qty2!=null && qty2.length()>0))
        {
            pst2.setTimestamp(1, timestamp);
            pst2.setString(2, porderno);
            pst2.setString(3, drug2);
            pst2.setInt(4, Integer.parseInt(qty2));
            pst2.addBatch();

            noofdrugs++;
        }

        if (drug3!=null && drug3.length()>0)
            && (qty3!=null && qty3.length()>0))
        {
            pst2.setTimestamp(1, timestamp);
            pst2.setString(2, porderno);
            pst2.setString(3, drug3);
            pst2.setInt(4, Integer.parseInt(qty3));
            pst2.addBatch();

            noofdrugs++;
        }

        if (drug4!=null && drug4.length()>0)
            && (qty4!=null && qty4.length()>0))
        {
            pst2.setTimestamp(1, timestamp);
            pst2.setString(2, porderno);
            pst2.setString(3, drug4);
            pst2.setInt(4, Integer.parseInt(qty4));
            pst2.addBatch();

            noofdrugs++;
        }

        if (drug5!=null && drug5.length()>0)
            && (qty5!=null && qty5.length()>0))
        {
            pst2.setTimestamp(1, timestamp);
            pst2.setString(2, porderno);
            pst2.setString(3, drug5);
            pst2.setInt(4, Integer.parseInt(qty5));
            pst2.addBatch();

            noofdrugs++;
        }

        if (noofdrugs>0) {
            pstmt.executeBatch();
        }

【讨论】:

    【解决方案2】:

    首先编写一个单独的函数将Items插入数据库。

        void insertItemReord(timestamp, porderno, drug, qty)
        {
            // SQL STUFF
        }
    

    然后适当地调用它。

           if((scom!=null && scom.length()>0)
                && (porderno!=null && porderno.length()>0)
                && (bdate!=null && bdate.length()>0)
            {
                pst.execute();
    
                if (drug1!=null && drug1.length()>0)
                    && (qty1!=null && qty1.length()>0))
                {
                    insertItemReord(timestamp, porderno, drug1, qty1);
                }
    
                if (drug2!=null && drug2.length()>0)
                    && (qty2!=null && qty2.length()>0))
                {
                    insertItemReord(timestamp, porderno, drug2, qty2);
                }
    
                if (drug3!=null && drug3.length()>0)
                    && (qty3!=null && qty3.length()>0))
                {
                    insertItemReord(timestamp, porderno, drug3, qty3);
                }
    
                if (drug4!=null && drug4.length()>0)
                    && (qty4!=null && qty4.length()>0))
                {
                    insertItemReord(timestamp, porderno, drug4, qty4);
                }
    
                if (drug5!=null && drug5.length()>0)
                    && (qty5!=null && qty5.length()>0))
                {
                    insertItemReord(timestamp, porderno, drug5, qty5);
                }
    
                  %>
                  <script language="javascript">
                        alert("Sucessfuly Sent to "+scom);
                  </script>
                  <%    
            }
    

    【讨论】:

      【解决方案3】:

      创建一个名为 utility 的包,然后在实用程序包中编写 DBconnection 代码。

      public class DBconnection {
      
      public static Connection getConnection() {// set the db connection
          boolean status = false;
          Connection conn = null;
          PreparedStatement pst = null;
          ResultSet rs = null;
      
          String url = "jdbc:mysql://localhost:3306/";
          String dbName = "login";
          String driver = "com.mysql.jdbc.Driver";
          String userName = "root";
          String password = "";
      
          try {
              Class.forName(driver).newInstance();
              conn = DriverManager.getConnection(url + dbName, userName, password);           
      
          } catch (Exception e){
              System.out.println(e);
          } finally {
            if (conn != null) {
                 try {
      
                  } catch (SQLException e) {
                      e.printStackTrace();
                  }
              }
              if (pst != null) {
                  try {
      
                  } catch (SQLException e) {
                   e.printStackTrace();
                  }
             }
              if (rs != null) {
                  try {
      
                  } catch (SQLException e) {
                      e.printStackTrace();
                  }
              }
          }
          return conn;
      }
      

      }

      然后创建一个新的 java 文件,将查询写入另一个包中。

      public class Registration {
      // new user registration method
      
      public static boolean register(String firstname,String lastname,String email,String username,String password) {
          Connection conn = null;
          PreparedStatement pst1, pst2;
          int rs1, rs2;
      
          boolean status = false;
          try {
              DBconnection dbops = new DBconnection();
              conn = dbops.getConnection();//create connection
              System.out.println("--getconnection-->new user");
              //inert values to the register table
              pst1 = conn.prepareStatement("INSERT INTO register(firstname,lastname,email,username,password) values(?,?,?,?,?)");
              pst1.setString(1, firstname);
              pst1.setString(2, lastname);
              pst1.setString(3, email);
              pst1.setString(4, username);
              pst1.setString(5, password);
              rs1 = pst1.executeUpdate();
      
              System.out.println("--Execute Query-->new user");
              //System.out.println(rs1);
              if (rs1 == 1) {
                  //insert values to users table
                  pst2 = conn.prepareStatement("INSERT INTO users(username,password) values(?,?)");
                  pst2.setString(1, username);
                  pst2.setString(2, password);
      
                  rs2 = pst2.executeUpdate();
                  if (rs2 == 1) {
                      System.out.println("inserted succesfully");
                      status = true;
                  } else {
                      System.out.println("not insert to users table - something went wrong");
                  }
              } else {
                  System.out.println("not insert to register table - username error");
                  status = false;
              }
      
          }catch(SQLException se) {
              //Handle errors for JDBC
              se.printStackTrace();
          } catch (Exception e) {
              //Handle errors for Class.forName
              e.printStackTrace();
          }finally {
              try {
                  conn.close();
              } catch (Exception e) {
              }
          }
          return status;
      }
      

      这个函数被一个 servlet 调用并返回一个布尔值。

      protected void doPost(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
      
          response.setContentType("text/html");
          PrintWriter out = response.getWriter();
      
          String firstname = request.getParameter("firstname");
          String lastname = request.getParameter("lastname");
          String email = request.getParameter("email");
          String username = request.getParameter("username");
          String password = request.getParameter("password");
      
          HttpSession session = request.getSession(false);
      
          if (Registration.register(firstname,lastname,email,username,password)) {
              out.print("<p style=\"color:red\">Account Created</p>");
              RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
              rd.forward(request, response);
          } else {
              out.print("<p style=\"color:red\">Error Occured In User Registration</p>");
              RequestDispatcher rd = request.getRequestDispatcher("newuser.jsp");
              rd.include(request,response);
          }
      

      jsp 是视图,servelet 是控制器,java 文件是模型。 我想你明白了。

      【讨论】:

        猜你喜欢
        • 2013-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-25
        • 1970-01-01
        • 1970-01-01
        • 2023-02-02
        • 2011-07-05
        相关资源
        最近更新 更多