importing CSV data into Database in java when the no of columns are known using javacsv

importing CSV data into Database in java when the no of columns are known using javacsv

I have imported CSV data into postgres Database in java using javaCSV jar. But now i have to convert it in such way that if the no of columns in the csv are not known then also i should be able to import it. But the condition i can use only javaCSv jar. No other jar is allowed. And also the performance should not degrade if i insert 100000 records. Here is my code-

DataImport.java

package programs;
public class DataImport {
            public static void main(String[] args) {
                        CSVLoader csvLoader=new CSVLoader();
            String fileName="D:/File1.csv";
            csvLoader.loadCSV(fileName);
                    }
}

CSVLoader.java

package programs;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class CSVLoader {
    static CSVToDB cd   = new CSVToDB();

    public CSVLoader(char seprator) {
        super();
        this.seprator = seprator;
    }

    public void loadCSV(String fileName) {
        CsvReader products = null;
        try {
            products = new CsvReader(fileName);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        cd.retrieveData(products);
        products.close();
    }


}

CSVTotDB.java

import java.io.FileInputStream;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

//import java.util.Properties;

import com.csvreader.CsvReader;

public class CSVToDB {

    void retrieveData(CsvReader products) {
        Connection c = null;
        PreparedStatement stmt = null;
        try {

            c = ConnectionManager.getConnection();
            System.out.println(products.readHeaders());

            System.out.println(products.getHeaderCount());
            String a;

            stmt = c.prepareStatement("insert into csvtodb values(?,?,?)");
            final int batchSize = 1000;
            int count = 0;
        while (products.readRecord()) {

                stmt.setString(1, products.get("Name"));
                stmt.setString(2, products.get("Address"));
                stmt.setString(3, products.get("City"));
                stmt.addBatch();
                if (++count % batchSize == 0) {
                    stmt.executeBatch();
                }
            }

            stmt.executeBatch();
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + " : " + e.getMessage());
            System.exit(0);
        } finally {
            try {

                products.close();
                stmt.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                c.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("Records created successfully");

    }
}

ConnectionManager.java

package programs;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionManager {
    private static Connection c = null;
    PreparedStatement stmt = null;
    private static String Driver = null;
    private static String url = null;
    private static String UserName = null;
    private static String Password = null;

    public static Connection getConnection() {
        Properties props = new Properties();
        try {
            props.load(new FileInputStream("src/Demo.properties"));

            Driver = props.getProperty("Driver");
            url = props.getProperty("connectionURL");
            UserName = props.getProperty("UserName");
            Password = props.getProperty("Password");
            Class.forName(Driver);
            c = DriverManager.getConnection(url, UserName, Password);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException ee) {
            // TODO Auto-generated catch block
            ee.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return c;
    }
}

Demo.properties

Driver=org.postgresql.Driver
connectionURL=jdbc:postgresql://localhost:5432/Test
UserName=postgres
[email protected]

Please reply as early as possible

View Answers

Ads









Related Tutorials/Questions & Answers:
importing CSV data into Database in java when the no of columns are known using javacsv
importing CSV data into Database in java when the no of columns are known using javacsv   I have imported CSV data into postgres Database in java... that if the no of columns in the csv are not known then also i should be able to import
Upload CSV File into Columns of sql table using servlets and jsp
Upload CSV File into Columns of sql table using servlets and jsp  Hello sir, plz give me the code to upload csv file data into respective columns of table
Advertisements
importing data and edit that data
importing data and edit that data   hello sir i have data in excel... that data like adding new columns and new rows and creating new tables with that data in the same database
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: file1.csv has 3 columns(VendorID,Name) file2.csv has 2 columns(VendorID,address
Exporting data from mysql into csv using jsp
Exporting data from mysql into csv using jsp  Hi friends.... I want to export the data from mysql to csv file using... i am having 30 columns in my database.. Eg- text1,text2,text3,....,upto text30... i want to export this data
how to make a radiobutton selected when retrieving data from database using struts framework and spring jdbc
how to make a radiobutton selected when retrieving data from database using struts framework and spring jdbc  how to make a radio button selected when retrieving data from database using struts framework and spring jdbc
code for selected checkbox columns data from database
code for selected checkbox columns data from database  in my page iam getting all column names of a particular table with checkboxes. when iam select one or more checkboxes i have to get data of that selected columns only. what
sending data to google chart api from mysql database using java
sending data to google chart api from mysql database using java  how to send data from mysql database to google chart api using java
Importing in java . . . .
Importing in java . . . .   We all know that when we are importing a class of a package in another package , the methods which are public are only available and we can use it . But suppose the method has default access specifier
Export data into CSV File using Servlet
Export data into CSV File using Servlet  ... to Export data into  CSV file using Servlet. We have created  file "JdbcCsvFile.java" to export data from this .java file.. Brief
How to Retrieve Data from the database and write into excel file using Java
How to Retrieve Data from the database and write into excel file using Java  Hi, I am trying to develop an small application where i trying to retrieve Data from the database and store the details in excel file. Please can
display data from database in textbox when id entered in textbox
display data from database in textbox when id entered in textbox  i wanted to enter data in textbox .depending on entered data in textbox data from database should be displayed dynamically in textbox
retrieve data from database using jsf
retrieve data from database using jsf  Hello I want an example of source code to retrieve data from database i have a database (oracle) name as db1 it's contain table 'author' composed of three columns idauthor(primary key
how to insert multiple columns of a single row into my sql database using jsp
how to insert multiple columns of a single row into my sql database using... sql database using jsp. when i click ADD ROW,rows are added.when i click submit the data in the row must be added into database. the following code
How to save database data into excelsheet using hibernate
How to save database data into excelsheet using hibernate  How to save database data into excelsheet using hibernate
insert data in the database using checkbox
insert data in the database using checkbox  i am fetching data from the database using servlet on the jsp page and there is checkbox corresponding... should i insert only checked data into database on submission.   We
sending data to google chart api from mysql database using java
sending data to google chart api from mysql database using java  Добовляйтесь в группу "МАЙНКРАФТА" Будьте участниками Группы Помогаите нам и себе Наша группа https://vk.com/club60851464 Есть свой сервер! Хорошая атмосфера
How to save form data to a csv file using jquery or ajax
How to save form data to a csv file using jquery or ajax  Please let...=data.responseText; Now the problem is ,i should write form data to a csv file using ajax... this. i am able to read the csv file using this code if (window.XMLHttpRequest
insert data using drop down box in java into database postgresql
insert data using drop down box in java into database postgresql  can... data into database using an drop down box .....as i m using eclipse as jdbc and postgresql as data base syntax which i m using is like:- java class
insert data using drop down box in java into database postgresql
insert data using drop down box in java into database postgresql  can... data into database using an drop down box .....as i m using eclipse as jdbc and postgresql as data base syntax which i m using is like:- java class
insert data using drop down box in java into database postgresql
insert data using drop down box in java into database postgresql  can... data into database using an drop down box .....as i m using eclipse as jdbc and postgresql as data base syntax which i m using is like:- java class
insert data using drop down box in java into database postgresql
insert data using drop down box in java into database postgresql  can... data into database using an drop down box .....as i m using eclipse as jdbc and postgresql as data base syntax which i m using is like:- java class
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, better knows as CSV is having a delimited data format. It has field/columns
retrieve data from database in java swing form using prev n next buttons
retrieve data from database in java swing form using prev n next buttons  i have a database having columns id(int),path(text),width(int),height(int... of various rows from database in labels by clicking previous and next
retrieve data from database in java swing form using prev n next buttons
retrieve data from database in java swing form using prev n next buttons  i have a database having columns id(int),path(text),width(int),height(int... of various rows from database in labels by clicking previous and next
How to export data from database to excel sheet by using java in standalone project
How to export data from database to excel sheet by using java in standalone project  How to export data from database to excel sheet by using java in standalone project
Expport data into CSV File using JDBC in Servlet
into CSV file using JDBC in Servlet. We have created  file "JdbcCsvFile.java" to export data from database in to CSV file. Brief... into CSV File using JDBC in Servlet   
how to insert data into database using jsp & retrive
how to insert data into database using jsp & retrive  Hello, I have created 1 html page which contain username, password & submit button. in my oracle10G database already contain table name admin which has name, password
storing csv into oracle database
storing csv into oracle database  i want jsp code for storing csv file into oracle database
create csv file in php in multiple columns
create csv file in php in multiple columns  i need create csv file in multiple columns like this: id name age date_added 1 john 23 2012-2-12 2 jane 25 2012-3-14 i can build csv file like this: id,name,age,date
create csv file in php in multiple columns
create csv file in php in multiple columns  i need create csv file in multiple columns like this: id name age date_added 1 john 23 2012-2-12 2 jane 25 2012-3-14 i can build csv file like this: id,name,age,date

Ads