title: How to uploading multiple csv file into mysql database using jsp and servlet?
body: <p>I have to upload multiple .csv files,like I have five text boxes and for each text boxe corresponding browse button will be there . When I click on submit button, it has to create table in mysql database with name of text box value, and this table has to updated with .csv file.please can any one suggest me to how to do it. </p>
  
  <p>thank you.</p>
  
  <p>here is my code.</p>
  
  <p>servlet.java:</p>
  
  <pre><code>   import java.io.File;
     import java.io.IOException;
     import java.io.PrintWriter;
     import java.util.Iterator;
     import java.util.List; 
     import javax.servlet.RequestDispatcher;
     import javax.servlet.ServletConfig;
     import javax.servlet.ServletException;
     import javax.servlet.http.HttpServlet;
     import javax.servlet.http.HttpServletRequest;
     import javax.servlet.http.HttpServletResponse;
     import org.apache.commons.fileupload.FileItem;
     import org.apache.commons.fileupload.FileUploadException;
     import org.apache.commons.fileupload.disk.DiskFileItemFactory;
     import org.apache.commons.fileupload.servlet.ServletFileUpload;
  
      public class CommonsFileUploadServlet1 extends HttpServlet {
  private static final String TMP_DIR_PATH=System.getProperty("user.home"); 
  private File tmpDir;
  private static final String DESTINATION_DIR_PATH ="/";
  private File destinationDir; 
  public void init(ServletConfig config) throws ServletException {
  
              super.init(config);
      tmpDir = new File(TMP_DIR_PATH);
      if(!tmpDir.isDirectory()) {
          throw new ServletException(TMP_DIR_PATH + " is not a directory");
      }
  
      String realPath =getServletContext().getRealPath(DESTINATION_DIR_PATH);
      destinationDir = new File(realPath);
  
  
  
  }
  
  protected void doPost(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {
  
      PrintWriter out = response.getWriter();
      response.setContentType("text/plain");
  
  
      DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
      /*
       *Set the size threshold, above which content will be stored on disk.
       */
      fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
      /*
       * Set the temporary directory to store the uploaded files of size above threshold.
       */
      fileItemFactory.setRepository(tmpDir);
  
      ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
      try {
          /*
           * Parse the request
           */
                  int check=0;
                  String name1[]=new String[30];
                  String name2[]=new String[30];
                  String name3[]=new String[30];
                  String filename[]=new String[30];
  
          List items = uploadHandler.parseRequest(request);
          Iterator itr = items.iterator();
          while(itr.hasNext()) {
              FileItem item = (FileItem) itr.next();
              /*
               * Handle Form Fields.
               */
              if(item.isFormField()) {
  
                                      if(item.getFieldName().equals("text1"))
                                      {
                                         String name1[i]=item.getString();
  
  
                                      }
                                      if(item.getFieldName().equals("text2"))
                                      {
                                          String name2[i]=item.getString();
  
                                      }
                                      if(item.getFieldName().equals("text3"))
                                      {
                                          String name3[i]=item.getString();
  
                                      }
                                      if(item.getFieldName().equals("check"))
                                      {
                                          check=Integer.parseInt(item.getString());
  
                                              }
  
              } else {
                  //Handle Uploaded files.
  
                                    String filename[i]=item.getName();
  
  
              }
                            i++;  
          }
  
                      request.setAttribute("name1",name1);
                      request.setAttribute("name2",name2);
                      request.setAttribute("name3",name3);
                      request.setAttribute("filename",filename);
  
  
                       if(check==1)
                      {
                      RequestDispatcher dispatcher = request.getRequestDispatcher("programmelink.jsp");
      if (dispatcher != null){
              dispatcher.forward(request, response);
      } 
                      }
  
  
             out.close();         
      }catch(FileUploadException ex) {
          log("Error encountered while parsing the request",ex);
      } catch(Exception ex) {
          log("Error encountered while uploading file",ex);
      }                       
  
  } 
  }
  </code></pre>
  
  <p>programmelink.jsp:</p>
  
  <pre><code>&lt;%@page import="com.hcu.mysql.connection.ConnectionDemo1"%&gt;
  &lt;%@include file="dbconnection.jsp"%&gt;
  &lt;%@page import="java.sql.*"%&gt;
  &lt;%@page import="java.io.OutputStream"%&gt;
  &lt;%@page import="java.io.FileOutputStream"%&gt;
  &lt;%@page import="java.io.InputStream"%&gt;
  &lt;%@page import="java.io.FileInputStream"%&gt;
  &lt;%@page import="java.io.File"%&gt;
  &lt;%@ page contentType="text/html;charset=UTF-8" language="java" %&gt;
  &lt;center&gt;
  &lt;table border="2"&gt;
  &lt;%
      String pname[]=(String[])request.getAttribute("name1");
      String saveFile[]=(String[])request.getAttribute("filename");
      Statement st1=con.createStatement();
      Statement st2=con.createStatement();
  
  
  try
    {
     int i;
      for(i=0;i&lt;pname.length;i++)
     {
  
   pname[i]=pname[i].replace('-', '_');
   String realPath =getServletContext().getRealPath("/");
  
  File f1 = new File(realPath+saveFile[i]);
  
  File f2 = new File("/var/lib/mysql/dcis_attendance_system/"+saveFile[i]);
  InputStream in = new FileInputStream(f1);
  
  OutputStream out1 = new FileOutputStream(f2);
  
  byte[] buf = new byte[1024];
  int len;
  
  while ((len = in.read(buf)) &gt; 0){
   out1.write(buf, 0, len);
  } 
  
  
  
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  System.out.println("driver connected");   
  
  st1.executeUpdate("create table if not exists "+pname[i]+"_curriculum(subjid      varchar(20),subjname varchar(100),credits varchar(20),semister varchar(20),sno INT) ");
  
  
    String qry2="LOAD DATA INFILE '"+saveFile[i]+"' INTO TABLE "+pname[i]+"_curriculum  FIELDS     TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n'  (subjid,subjname,credits,semister,sno)"; 
  
  st2.executeUpdate(qry2);   
  
  }
      out.println("&lt;center&gt;&lt;h1&gt;File uploaded sucessfully&lt;/h1&gt;&lt;/center&gt;"); 
   }
    catch(Exception e)
                         {
        out.println("&lt;center&gt;&lt;h1&gt;File not uploaded sucessfully&lt;/h1&gt;&lt;/center&gt;");
  
    }
       %&gt;
  &lt;/table&gt;
  &lt;/center&gt;
  </code></pre>
  
  <p>jsppage.jsp</p>
  
  <pre><code> &lt;form action="servlet" enctype="multipart/form-data" method="POST"&gt;
                  &lt;input type="hidden" name="check" value="7" /&gt;   
  
  
  
      &lt;/table&gt;
  
           &lt;table align="center" border="1" id="table1"&gt;
          &lt;tr&gt;
  
              &lt;td class="heading" align="center"&gt;Programme Name&lt;/td&gt;
              &lt;td class="heading" align="center"&gt;Programme Code&lt;/td&gt;
              &lt;td class="heading" align="center"&gt;Browse Curriculum&lt;/td&gt;
              &lt;/tr&gt;
              &lt;%int i;
              for(i=0;i&lt;2;i++)
  
              {
              %&gt;
              &lt;tr&gt;
                  &lt;td&gt;&lt;input type="text" name="text1"  size="11"  value=""&gt; &lt;/td&gt; 
                  &lt;td&gt;&lt;input type="text" name="text2"  size="10" value=""&gt; &lt;/td&gt;
                  &lt;td&gt;&lt;input type="file" name="file1" class="multi" id="file"&gt;&lt;/td&gt;
             &lt;/tr&gt; 
             &lt;%}%&gt;
             &lt;/table&gt;
  
             &lt;table align="center"&gt;
              &lt;tr&gt;
                  &lt;td&gt;&lt;input type="submit" name="submit" value="submit"&gt;&lt;/td&gt;&amp;nbsp;
                  &lt;td&gt;&lt;input type="button" name="add" value="Add" onclick="next();"&gt;&lt;/td&gt;&amp;nbsp;
              &lt;/tr&gt;                             
          &lt;/table&gt;
  
      &lt;/form&gt;
  </code></pre>