I m trying insert multiple rows in same database (each row had many fields) on submit but unable to do so. I m successfully able to insert single row but when it comes for multiple rows I got stuck.

This is the jsp page where you take an input to dynamically add no of rows. There is no separate submit button for each row instead single submit button to insert all rows.

1.> projmgrsuccessful.jsp

<form name="allocate-project-task" action="AddProjectTaskDAO" method="get"  enctype="multipart/form-data">
<h4>Another popup</h4>
<input type="hidden" name="proj_emp_comt" value="">
<input type="hidden" name="pid" value="<c:out value="${pid}" />">

<label>Enter the no of employee involved in project</label>
<input type="text" id="textbox1" />
<input type="button" value="Add" id="add" />

<table border="1" id="pt-tabledata">
</table>

<center><input type="submit" name="alloc_time" value="Allocate"><a href="#"  id="closea">Close</a></center>
</form>
<script>
$("#add").click(function() {
$('#pt-tabledata').append('<tr><td>Username</td><td>Work description</td> <td>Allocate time</td><td>Allocate work and time</td></tr>');
for (var i = 0; i < $("#textbox1").val(); i++) {
    $newdiv2 = $('<tr id="pt-ip-row" style="display:block;"><td><select name="uname"><c:forEach items="${ual}" var="u"><option value="<c:out value="${u.uname}"></c:out>"><c:out value="${u.uname}"></c:out></option> </c:forEach>              </select></td><td><textarea rows="5" cols="15" name="pdesc_emp"></textarea></td><td><input type="text" name="pestd_time_alloc" /></td><td></td><td><a href="#" id="close-pt-row" onclick="return hide();">Close</a></td> </tr>').after("#add");
    $('#pt-tabledata').append($newdiv2);
}
});
</script>

This is java code snippet where I processing the data like connecting to the database and inserting it into database table.

2.> AddProjectTaskDAO.java

package com.pms.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection; 
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class AddProjectTaskDAO
*/
@WebServlet("/AddProjectTaskDAO")
public class AddProjectTaskDAO extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public AddProjectTaskDAO() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    response.setContentType("text/html");  
    PrintWriter pw = response.getWriter(); 

    Connection conn=null;
    String url="jdbc:mysql://localhost:3306/";
    String dbName="projectmanagement";
    String driver="com.mysql.jdbc.Driver";
    String dbUsername="root";
    String dbPassword="root";

    try{  

          String Projid=" ";
          String Projuname=" ";
          String Projdesc_emp=" ";
          String Projestd_time_alloc=" ";
          String Projtask_emp_comment=" ";
          String Pid[] = request.getParameterValues("pid");  
          String Uname[] = request.getParameterValues("uname");  
          String Pdesc_emp[] = request.getParameterValues("pdesc_emp"); 
          String Pestd_time_alloc[] =  request.getParameterValues("pestd_time_alloc");
          String Projtask_emp_cmnt[] = request.getParameterValues("ptask_emp_cmnt");  
          //String Utype = request.getParameter("utype");

          for(int i=0; i<100; i++){
              Projid=Pid[i]+" "+ 1;
              Projuname=Uname[i]+" "+ 1;
              Projdesc_emp=Pdesc_emp[i]+" "+ 1;
              Projestd_time_alloc=Pestd_time_alloc[i]+" "+ 1;
              Projtask_emp_comment=Projtask_emp_cmnt[i]+" "+ 1;
              }

          Class.forName(driver);  
          conn = DriverManager.getConnection(url+dbName,dbUsername, dbPassword);
          Statement st=conn.createStatement();


          int i = st.executeUpdate("insert into projtaskallocate (pid,uname,ptdesc_emp,ptestd_time_alloc,ptask_emp_cmnt) values ('" +Projid+ "','" +Projuname+"','" +Projdesc_emp+ "','" +Projestd_time_alloc+ "','" +Projtask_emp_comment+ "')");

          String msg=" ";
          if(i!=0){  
          UserPMDAO dd = new UserPMDAO();
          request.setAttribute("ual", dd.getUsers());
          ProjectDAO pp = new ProjectDAO();
          request.setAttribute("pal", pp.getProjects());  
          String nextJSP = "/projmgrsuccessful.jsp"; 
          RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP); 
          dispatcher.forward(request,response);



          }  
          else
          {  
              msg="Failed to Add Project";
              pw.print("<font size='6' color=blue>" + msg + "</font>");
          }  
          pw.close();
          //pst.close();
          st.close();
          conn.close();
        }  
        catch (Exception e)
        {  
        e.printStackTrace(); 
        }  

}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub



}

}

Here the the problem is when I click on submit button only first row is inserted but my requirement is to insert all the rows.

Please help and if I m going wrong please guide me.

you are not looping over this line:

  int i = st.executeUpdate("insert into projtaskallocate (pid,uname,ptdesc_emp,ptestd_time_alloc,ptask_emp_cmnt) values ('" +Projid+ "','" +Projuname+"','" +Projdesc_emp+ "','" +Projestd_time_alloc+ "','" +Projtask_emp_comment+ "')");

so it's clear why it only inserts one row.

Even when I m looping, I receive java.lang.NullPointerException exception

and how did you implement the loop? which variable was null?

Yes, I have implemented this in a loop like this

              int j=0;
              for (int i=0;i<100;i++) {
              j = st.executeUpdate("insert into projtaskallocate (pid,uname,ptdesc_emp,ptestd_time_alloc,ptask_emp_cmnt) values ('" +Projid+ "','" +Projuname+"','" +Projdesc_emp+ "','" +Projestd_time_alloc+ "','" +Projtask_emp_comment+ "')");
              }

which is pointless. you will just insert the same values 100 times.
but next to that: which variable was null?

I am trying to figure it out which variable was null but unable to get it.
This is the complete code

package com.pms.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AddProjectTaskDAO
 */
@WebServlet("/AddProjectTaskDAO")
public class AddProjectTaskDAO extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddProjectTaskDAO() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub


    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub


        response.setContentType("text/html");  
        PrintWriter pw = response.getWriter(); 

        Connection conn=null;
        String url="jdbc:mysql://localhost:3306/";
        String dbName="projectmanagement";
        String driver="com.mysql.jdbc.Driver";
        String dbUsername="root";
        String dbPassword="root";

        try{  

              String Projid=" ";
              String Projuname=" ";
              String Projdesc_emp=" ";
              String Projestd_time_alloc=" ";
              String Projtask_emp_comment=" ";
              String Pid[] = request.getParameterValues("pid");  
              String Uname[] = request.getParameterValues("uname");  
              String Pdesc_emp[] = request.getParameterValues("pdesc_emp"); 
              String Pestd_time_alloc[] = request.getParameterValues("pestd_time_alloc");
              String Projtask_emp_cmnt[] = request.getParameterValues("ptask_emp_cmnt");  

              for(int i=0; i<100; i++){
                  Projid=Pid[i]+" "+ 1;
                  Projuname=Uname[i]+" "+ 1;
                  Projdesc_emp=Pdesc_emp[i]+" "+ 1;
                  Projestd_time_alloc=Pestd_time_alloc[i]+" "+ 1;
                  Projtask_emp_comment=Projtask_emp_cmnt[i]+" "+ 1;
                  }

              Class.forName(driver);  
              conn = DriverManager.getConnection(url+dbName,dbUsername, dbPassword);
              Statement st=conn.createStatement();

              int j=0;
              for (int i=0;i<100;i++) {
              j = st.executeUpdate("insert into projtaskallocate (pid,uname,ptdesc_emp,ptestd_time_alloc,ptask_emp_cmnt) values ('" +Projid+ "','" +Projuname+"','" +Projdesc_emp+ "','" +Projestd_time_alloc+ "','" +Projtask_emp_comment+ "')");
              }

              String msg=" ";
              if(j!=0){  
              UserPMDAO dd = new UserPMDAO();
              request.setAttribute("ual", dd.getUsers());
              ProjectDAO pp = new ProjectDAO();
              request.setAttribute("pal", pp.getProjects());  
              String nextJSP = "/projmgrsuccessful.jsp"; 
              RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP); 
              dispatcher.forward(request,response);


                  //pw.println("<input type='button' value='Back' onclick='history.back()'>");
              }  
              else
              {  
                  msg="Failed to Add Project";
                  pw.print("<font size='6' color=blue>" + msg + "</font>");
              }  
              pw.close();
              //pst.close();
              st.close();
              conn.close();
            }  
            catch (Exception e)
            {  
            e.printStackTrace(); 
            }  

    }

}

and you are sure the problem is in this line

j = st.executeUpdate("insert into projtaskallocate (pid,uname,ptdesc_emp,ptestd_time_alloc,ptask_emp_cmnt) values ('" +Projid+ "','" +Projuname+"','" +Projdesc_emp+ "','" +Projestd_time_alloc+ "','" +Projtask_emp_comment+ "')");

looks like st is null.

does it run once and then becomes null-referenced, or doesn't it run at all?

st should not be null but what is the reason behind I m unable to get it.
Secondly earlier I was able to insert one row but now unable to insert any row.
Thirdly when I sysout values to check the values which were going for insertion but unable to get those values also

I got reason why I was receiving NullPointerException because request.getParameterValues() was unable to get the values.
This was also may be because I have dynamically created textboxes.
Please can help me out how to get textbox values from dynamically created textboxes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.