Home Answers Viewqa JSP-Servlet how to read the values for text and csv files and store those values into database in multiple rows..means one value for one row

 
 


sridivya pathaneni
how to read the values for text and csv files and store those values into database in multiple rows..means one value for one row
4 Answer(s)      a year and 9 months ago
Posted in : JSP-Servlet

Hai,

I need a program by using servlets.. the program is like this

i upload a text and csv file.it was stored in perticular directory now i have to read the stored(.csv or .txt) file and get the values from that file and store them into database table in multiple rows(which means one value for one row).

eg: my file containes the data as content of file ==> siva,divya,ravi

now it should stored in database like names(column)

siva divya

ravi

one value for one row.... can any one help in this program?

Regards, P.Divya

View Answers

August 12, 2011 at 1:56 AM


hi sridivya,

Just follows the steps which I have mentioned below. I have created this project in eclipse

Setup database

Here, I used MySql database, so type the following queries in mysql

create database test;
use test
create table namelist(name varchar(20));

Required files

1. uploadform.jsp
2. Upload.java (Servlet)
3. confirm.jsp
4. UpdateDB.java (Servlet)
5. error.jsp
6. namelist.csv

Required library

1.javacsv.jar
2.mysql-connector-java-5.1.10-bin.jar

You can download these library from  
[mysql driver][1]  
[CSVparser][2]

Add the above library to "ContextRoot/WEB-INF/lib/" directory to use servlet

Coding

1. uploadform.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Upload file</title>
    </head>
    <body>
        <form action="upload" enctype="multipart/form-data" method="post">
            <table border="1">
                <tr>
                    <td>CSV or TXT file:</td>
                    <td><input type="file" name="csvfile" /></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="submit"></td>
                </tr>
            </table>            
        </form>
    </body>
    </html>


2. Upload.java (Servlet)

    package com.file;

    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.PrintWriter;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
     * Servlet implementation class UploadServlet
     */
    public class Upload extends HttpServlet {
        private static final long serialVersionUID = 1L;
        PrintWriter out;
        private void setOut(PrintWriter out){
            this.out = out;
        }

        private void println(String content){
            out.print(content+"\n");
        }
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
            setOut(response.getWriter());
            boolean done = false;
            //to get the content type information from JSP Request Header
            String contentType = request.getContentType();

            //here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
            if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
                DataInputStream in = new DataInputStream(request.getInputStream());
                //we are taking the length of Content type data
                int formDataLength = request.getContentLength();
                byte dataBytes[] = new byte[formDataLength];
                int byteRead = 0;
                int totalBytesRead = 0;
                //this loop converting the uploaded file into byte code
                while (totalBytesRead < formDataLength) {
                    byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                    totalBytesRead += byteRead;
                    }

                String file = new String(dataBytes);

                //for saving the file name
                String saveFile = file.substring(file.indexOf("filename=\"") + 10);
                saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
                saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));

                int lastIndex = contentType.lastIndexOf("=");
                String boundary = contentType.substring(lastIndex + 1,contentType.length());
                int pos;
                //extracting the index of file 
                pos = file.indexOf("filename=\"");
                pos = file.indexOf("\n", pos) + 1;
                pos = file.indexOf("\n", pos) + 1;
                pos = file.indexOf("\n", pos) + 1;
                int boundaryLocation = file.indexOf(boundary, pos) - 4;
                int startPos = ((file.substring(0, pos)).getBytes()).length;
                int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

                if(saveFile.endsWith(".txt") || saveFile.endsWith(".csv")){
                    // creating a new file with the same name and writing the content in new file
                    FileOutputStream fileOut = new FileOutputStream(new File("../uploads/"+saveFile));
                    fileOut.write(dataBytes, startPos, (endPos - startPos));
                    fileOut.flush();
                    fileOut.close();
                    done = true;
                    getServletContext().setAttribute("fileName", saveFile);             
                    request.setAttribute("fileName", saveFile);
                }else{
                    request.setAttribute("error", "Unsupported file format");
                }
            }
            if(done)
                request.getRequestDispatcher("confirm.jsp").forward(request, response);
            else
                request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    }


3. confirm.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Success Page</title>
    </head>
    <body>
        <%=request.getAttribute("fileName") %> is uploaded successfully.
        <a href="updatedb">Click here to update database</a>
    </body>
    </html>

4. updatedb.java (Servlet)

    package com.db;

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

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import com.csvreader.CsvReader;

    /**
     * Servlet implementation class UpdateDatabase
     */
    public class UpdateDatabase extends HttpServlet {
        private static final long serialVersionUID = 1L;

        /**
         * @see HttpServlet#HttpServlet()
         */
        public UpdateDatabase() {
            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
            PrintWriter out = response.getWriter();
            try {           
                String filename = (String) getServletContext().getAttribute("fileName");
                out.println("FileName : "+filename);
                CsvReader products = new CsvReader("../uploads/"+filename);
                products.readHeaders();

                Class.forName("com.mysql.jdbc.Driver");
                Connection con = DriverManager.getConnection("jdbc:mysql://localhost/stack", "root", "");
                Statement st = con.createStatement();

                while (products.readRecord())
                {
                    String productID = products.get("ProductID");
                    String productName = products.get("ProductName");
                    String supplierID = products.get("SupplierID");
                    String categoryID = products.get("CategoryID");
                    String quantityPerUnit = products.get("QuantityPerUnit");
                    String unitPrice = products.get("UnitPrice");
                    String unitsInStock = products.get("UnitsInStock");
                    String unitsOnOrder = products.get("UnitsOnOrder");
                    String reorderLevel = products.get("ReorderLevel");
                    String discontinued = products.get("Discontinued");             

                    String query = "insert into product values ("; 
                    query += productID+", '";
                    query += productName+"', ";
                    query += supplierID+", ";
                    query += categoryID+", '";
                    query += quantityPerUnit+"', ";
                    query += unitPrice+", ";
                    query += unitsInStock+", ";
                    query += unitsOnOrder+", ";
                    query += reorderLevel+", '";
                    query += discontinued+"')";

                    out.println("Query : "+query);
                    st.executeUpdate(query);
                }
                out.println("Data inserted...");
                products.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } 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
        }

    }


5. error.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Fail Page</title>
    </head>
    <body>
        <%=request.getAttribute("error") %>
        Choose correct file format <br />
        <a href="uploadform.jsp">Upload file</a>
    </body>
    </html>

6. namelist.csv 

    name
    siva
    divya
    ravi

Regards,
M.Sriram

August 12, 2011 at 8:31 AM


Hi,
There was an error in the above demo. Need to change database and namelist.csv file.

Setup database
    create database stack;
    use stack
    create table product(ProductID int, ProductName varchar(20), SupplierID int, CategoryID int, QuantityPerUnit varchar(50), UnitPrice int, UnitsInStock int, UnitsOnOrder int, ReorderLevel int, Discontinued varchar(8));

**6. namelist.csv**

    ProductID,ProductName,SupplierID,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,UnitsOnOrder,ReorderLevel,Discontinued
    1,Chai,1,1,10 boxes x 20 bags,18,39,0,10,FALSE
    2,Chang,1,1,24 - 12 oz bottles,19,17,40,25,FALSE

August 12, 2011 at 12:35 PM


can u tel me the file size limit for this program?

Regards, P.Divya


August 12, 2011 at 9:45 PM


Which file are you asking about? csv file?

Regards,
M.Sriram









Related Pages:
how to read the values for text and csv files and store those values into database in multiple rows..means one value for one row
how to read the values for text and csv files and store those values into database in multiple rows..means one value for one row  Hai, I need... table in multiple rows(which means one value for one row). eg: my file containes
retrieve multiple columns values from multiple csv files in java
retrieve multiple columns values from multiple csv files in java  Suppose there is folder in C:\fileupload which contains these two csv files... these two files and store in oracle database as: VendorID,Name,Address and plz
How to store two integer value in a separate file and retrieve those values
How to store two integer value in a separate file and retrieve those values  I need to save two values so i can use those values later i came up with idea of saving those values in a separate file and updating values in file
how to store multiple values from drop down in database where i am using java struts 1.3
how to store multiple values from drop down in database where i am using java... where i have to select multiple keyskills. but it is taking only one valuee.. i... is displaying.. i need code in java so that it takes multiple values
How to read and retrieve jtable row values into jtextfield on clicking at particular row ...
How to read and retrieve jtable row values into jtextfield on clicking at particular row ...  Hello Sir, I am developing a desktop... to read all the values of particular row at which mouse is clicked. and display
How to fetch entries/values from database to a jsp page one by one?
How to fetch entries/values from database to a jsp page one by one?  I have a table in Microsoft SQL server Management Studio with two columns title... to display different database entries of the each column in different blocks. Now
how can i store text box values as it is in database table
how can i store text box values as it is in database table  CUSTOMER DESCRIPTION
how can retrieve more than one values in text field using ajax?
how can retrieve more than one values in text field using ajax?  im...($result)) { echo "<input name='seat' type='text' value=".$row['Seat_Number... first then in mysql db retrieve seat numbers 1,2,3,4 in text boxes problem
How to pass multiple values from a servlet to JSP?
How to pass multiple values from a servlet to JSP?  hi, I want to pass multiple values form a servlet to JSP. Hw do i do that? I am able to send one value at a time without any prb, but I am unable to carry multiple (from two
Works only for one row
Works only for one row   Hi, My below code is working only if there is a single row. could you please help me in doing it for all the rows...; <td><center><input type="text" value="<%=rs.getString
JPA One-to-One Relationship
a single value association to another entity.  One-to-One: In one-to-one... the following files: Database Table:  person address... JPA One-to-One Relationship   
how to get multiple hyperlink values from a table column to another jsp file?
how to get multiple hyperlink values from a table column to another jsp file?  dear sir: this is what i'm trying to do, i have 3 JSP files. first... for the user string in the database, as a result a table will come up with 3 columns itemid
Java Read CSV file
Java Read CSV file In this tutorial, you will learn how to read csv file. CSV... and there is no need of using any API to read these files. In the given example, we have... the row data into the array where each token is represented as each cell value
How to delete the row from the Database by using servlet
How to delete the row from the Database by using servlet  Dear Sir/Madam I am trying to delete the one user data in the Oracle SQL server database...: Delete row from database using servlet   In that link solution
phpmyadmin - upload csv files - SQL
phpmyadmin - upload csv files  i have database in phpmyadmin. i have upload one time in csv file. i need to another csv file in upload same table. i will try to do this but result is failed. (table rows and csv rows are same
How to store values in a database using JSTL? - JSP-Servlet
How to store values in a database using JSTL?  I want to store values in a database... How can i store in database? Here is my code... This wil extract details and displays in a table format... Now i want to store these values
how to store a dynamic values - JSP-Servlet
how to store a dynamic values  Dear sir, i have a ArrayList in that i have stored a values from a excel sheet specified column values and i have one string that is as follows Dear ~2 , Your cl is ~3 ,el is ~4
Arraylist from row values
Arraylist from row values  Hello, can anyone please help on how to make an arraylist from the row values of a particular column from a database table? Thanks in advance!   import java.sql.*; import java.util.ArrayList
How to Dragging and dropping HTML table row to another position(In Jsp) and save the new position (values) also in database(MySql)?
table)from Database, Now i am Dragging and dropping one HTML table row to another...How to Dragging and dropping HTML table row to another position(In Jsp) and save the new position (values) also in database(MySql)?  Hi members, I
To Retain the values entered in the text box after submit in jsp page
down. The functionality is when user enters comma separated values in those text... given all those. Now my problem is how can i retain those values entered in box...To Retain the values entered in the text box after submit in jsp page  
store dropdown box values in database server
store dropdown box values in database server  how to store dropdown box values in database server in jsp
How to Display values from databse into table
How to Display values from databse into table  I want to display values from database into table based on condition in query, how to display that? For example i have some number of books in database but i want to display books
Files
Files  Read the text below from a file and store values in a Map as mentioned below..and display amount based on input(number) Map<K,V> = Map <Number , Rate> take number as key and rate as value.. File.Txt Number
how to read values from excel sheet and compare with database using jsp
how to read values from excel sheet and compare with database using jsp  hi sir i am arun how to read values from excel sheet and compare...,serialno) values of excelsheet we have to compare with database value if these 3
problem in setting the values from database
problem in setting the values from database  hello friends, can anyone help me?? I am facing this problem for past one week. I could't set the values from database. here is the code: private JTextField getJTextField1
fetch values from database into text field
fetch values from database into text field  please provide the example for fetching values from database into text field of table wth edit...;"); out.println("<td><input type=\"text\" name=\"LASTNAME\" value
Dragging and dropping HTML table row to another position(In Jsp) and save the new position (values) also in database
Database, Now i am Dragging and dropping one HTML table row to another position.I want to save the position ( new position) in database(MySql).How to do this?Please... the new position (values) also in database  Hi members, I have one Html
Uploading the multiple files
. For uploading the multiple files at a time, first create a table as per required..., input type as submit, name as submit and value as upload. close the table one... in bold letters like "Multiple File Upload" Now, select the file one
store values of drop down list box in database
store values of drop down list box in database  how to store values of drop down list box in oracle database in jsp?I have information inserting form where i have date of birth as drop down list box
Hibernate One-to-one Relationships
. One-to-One Relationships In case of one-to-one relationships, each row in table A linked to only one row in table B. Here we will implement one-to-one..._id) values (?, ?, ?) Done In this section we learned about the one
read text file and store the data in mysql - JDBC
read text file and store the data in mysql  when we store the data in mysql table from text file its store the data from new line to new column. how to store the data in different column from a single line of text file. 
send multiple textbox vaues in to an jsp form to store them in a DB table
send multiple textbox vaues in to an jsp form to store them in a DB table  Hi sir... I am not getting how can i send the multiple input text box values in to an jsp file with additional values to store those values
How to insert and update all column values of database from jtable.
How to insert and update all column values of database from jtable.  ... // If we are here, we have read one entire row of data. Do... ,update,delete database values from jtable only so i added three buttons add,update
How to insert and update all column values of database from jtable.
How to insert and update all column values of database from jtable.  ... // If we are here, we have read one entire row of data. Do... ,update,delete database values from jtable only so i added three buttons add,update
How to store extracted values from xml in a database? - XML
How to store extracted values from xml in a database?  I want to store extracted xml values in a database... How can i store extacted xml values in a database... give me a example
How to store extracted values from xml in a database? - XML
How to store extracted values from xml in a database?  I want to store extracted xml values in a database... How can i store extacted xml values in a database... give me a example
how to store array values into two different tables in java?
how to store array values into two different tables in java?  I have... and now I want to store these values in two different tables(i.e store 2 array values in one table and remaining two values in another table
Store values of dynamically generated textboxes into database
Store values of dynamically generated textboxes into database   I'm... for example the user enters 3 into textbox, three text boxes get generated in the new frame. now when the user write data into these text boxes I want
To Upload and insert the CSV file into Database
To Upload and insert the CSV file into Database... to upload a CSV file through JSP and insert it into the database. For this, we have... = pst.executeUpdate("insert into file(file_data) values('"+value
Inserting values in MySQL database table
to insert the values in the database. Here we are going to see, how we can insert values in the MySQL database table. We know that tables store data in rows... to insert values in the database table with appropriate value. Here
reading the records from a .xlsx file and storing those records in database table
reading the records from a .xlsx file and storing those records in database table  Here is my requirement, I want to read the records from a .xlsx file and store that records in database table. I tried like this public class
JPA One-to-Many Relationship
the one-to-many relationship and how to develop a one-to-many relation in your JPA... through the files: parentId and childrenId. In the parentchild table, the one... database table.] You see the following image that represents one-to-many
Updating multiple value depending on checkboxes
Updating multiple value depending on checkboxes  Hi .. I want to Update the multiple values of database using checkboxes and want to set the session for selected checkboxes..? please answer if any one knows as soon as possible
JPA Many-to-one Relationship
about the many-to-one relationship and how to develop a many-to-one relation..., the one parentId has different childrenId. [Note: If in the database hasn't... the value in your database table.] You see the following image that represents
JDBC and Aggregate values
JDBC and Aggregate values  How to get the aggregate value using JDBC... only one row, only one column in return and I want to get that data using JDBC. How may I do it?   Java JDBC retrieve selected value import java.sql.
Export Database table to CSV File
Export Database table to CSV File In this tutorial, you will learn how to retrieve data from database and save it to CSV File. The Comma-separated values... similar to text files. Exporting or writing data to csv file is exactly same
help me plz:-Merge multiple jasper files into Single one
help me plz:-Merge multiple jasper files into Single one  how to Merge multiple jasper files into Single one word doc
Java Multiple Insert Query
and in the other table we will store the multiple selected value of dropdown list... the value after selecting the multiple values from the dropdown list...Java Multiple Insert Query In this example we will discuss about how
Query to insert values in the empty fields in the last row of a table in Mysql database?
Query to insert values in the empty fields in the last row of a table in Mysql database?  I have some fields filled and some fields empty in the last row of my MYSQL database. Now I want to fill up those empty fields in the last
Write the Keys and Values of the Properties files in Java
will learn how to add the keys and it's values of the properties files in Java. You know the properties files have the the keys and values of the properties files... Write the Keys and Values of the Properties files in Java

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.