skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Saturday, October 20, 2012

Convertion of CSV to Table

Posted by Raju Gupta at 4:30 PM – 0 comments
 
It converts the comma seperated value file to a table in database.

/*
 * This program used to convert data from CSV file to TABLE

 */

import java.sql.*;
import java.io.*;
public class ConvertCSVtoTABLE {
    
    public void covertCsvtotable(String file)
    {
        Connection conn;
        conn=null;
        ResultSet rs;
        Statement stmt;
        String Query="";
        try
        {
            /*****This program connect with MS-ACCESS DATABASE******/
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            conn=DriverManager.getConnection("jdbc:odbc:DB");
            stmt = conn.createStatement();
             /******************************************************/
      
            
            int noofcolumn=1,b,bprev,i;
            String text1="'";
            String filename=file;
            FileReader fin=new FileReader(filename);
            BufferedReader bf=new BufferedReader(fin);
            b=bf.read();
            while(b!=-1){
                bprev=b;
                if(b==44)
                {
                    text1=text1+"'";
                    noofcolumn=noofcolumn+1;
                }
                if(b==10)
                {
                     text1=text1+"'";
                     Query="insert into temptable(";
                     for(i=1;i<noofcolumn;i++)
                         Query=Query+"col"+i+",";
                     Query=Query+"col"+i;
                     Query=Query+") values("+text1+")";
                     stmt.executeUpdate(Query);
                     text1="'";
                     noofcolumn=1;
               }
               if(b!=34 && b!=10)
                {
                     text1=text1+(char)b;
                }
               b=bf.read();
               if(bprev==44)
                     text1=text1+"'";
             }
            
            fin.close();
            bf.close();
            conn.close();
            System.out.println("Data Transferred from CSV to TempTable Successfully :)");
         }
  
        catch(Exception E)
        {
             System.out.println(E);
        }        
    }
    
  public static void main(String[] args) 
    {
          ConvertCSVtoTABLE C=new ConvertCSVtoTABLE();
          C.covertCsvtotable("C:\Users\Raj\input.csv");
        
    }
}

Labels: CSV Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger