How to Upload CSV file into Ms-Access Database table

hi friends

Could anyone Post some simple code to Upload the CSV file content into Databse table.

I got the Following code from a Thread's Link. But i am not able to understand it. Since Because i am Quite new To java. so Could anyone help me Please

The Code what i got is this

import java.util.Iterator;

import java.util.List;

publicclass FileUtils{

// CSV content formatter --

publicstaticbyte[] formatCsv(List csvList){

// If CSV content is null, return null.

if (csvList ==null){

returnnull;

}

StringBuffer csvContent =new StringBuffer();

// Process records.

for (Iterator iter = csvList.iterator(); iter.hasNext();){

List record = (List) iter.next();

if (record !=null){

csvContent.append(formatCsvRecord(record));

}

// Add system default newline.

csvContent.append(System.getProperty("line.separator"));

}

return csvContent.toString().getBytes();

}

// CSV record formatter

privatestatic String formatCsvRecord(List record){

String fields ="";

// Process fields.

for (Iterator iter = record.iterator(); iter.hasNext();){

Object object = iter.next();

if (object !=null){

String field = object.toString();

if (field.indexOf('"') > -1){

field = field.replaceAll("\"","\"\"");// Escape quotes.

}

if (field.indexOf(';') > -1 || field.indexOf('"') > -1){

field ="\"" + field +"\"";// Surround with quotes.

}

fields += field;

}

if (iter.hasNext()){

fields +=";";// Add field separator.

}

}

return fields;

}

}

i hava a CSV File with Three Column, in the Databse table i have the Same three field calledName, age, Occupation. Now i want to upload the record from CSV to Database table.

give me some sample code.

Thank you for your service

Cheers

Jofin

[3948 byte] By [jofin123a] at [2007-11-27 2:09:41]
# 1
Hi Friends Could anyone Please help me on this issue?. i am really need of your helpThank you for your serviceCheersJofin
jofin123a at 2007-7-12 2:00:25 > top of Java-index,Java Essentials,Java Programming...
# 2

Where are you coming from pgm'g wize? How much Java pgm'g have you done? What type of application is this to be? ... class assignment? JSP? background job?

You will need JDBC for the DB work. And you already know you need to split up the rows of the .csv file. You could use either a BufferedReader or a Scanner for the file reading, depending on your version of Java - Scanner is 1.5.x and up only.

abillconsla at 2007-7-12 2:00:25 > top of Java-index,Java Essentials,Java Programming...
# 3
> Could anyone Please help me on this issue?. i am really need of your helpI gave you help in this posting and you didn't appreciate it, so you are on your own. http://forum.java.sun.com/thread.jspa?threadID=5164347
camickra at 2007-7-12 2:00:25 > top of Java-index,Java Essentials,Java Programming...
# 4

Hi

Sorry for not replying to that Thread

http://forum.java.sun.com/thread.jspa?threadID=5164347

For this application i am Using Java1.6. what i want is i want to read CSV File which has three Cloumn and Put those content into Database table wchich has three Fields Name, age, Occupation

I am using Swing for my application. Through User interface i have to select the CSV File and Click on a Button Import then the Content of CSV should be uploaded into Database table.

Please somebody give me a sample coding. so that i can Understand Better

Thank you very much for your service

Cheers

Jofin

jofin123a at 2007-7-12 2:00:25 > top of Java-index,Java Essentials,Java Programming...
# 5

You did not answer any of my questions. It's helpful to know precisely where a poster is coming from - how much help they need - what they already know. Too often OPs either get irritated because others trying to help guess wrongly and either tell/show the poster things they already know, or because they don't give the OP enough information, the OP gets frustrated.

abillconsla at 2007-7-12 2:00:25 > top of Java-index,Java Essentials,Java Programming...
# 6

Hi

I am a student, Studiing BCA, Just now i am trying to Learn java. Now i have learned Core Java a Little bit and then Trying to Learn java Swing. I am doing a Library System. for that i want to Import the Student List into Database. I know the JDBC. Concept, I heard If i Use CSV it will be easier to read students record into the Database table.

Could you please give a Sample code to import CSV File into Database

Thank you for your service

Cheers

Jofin

jofin123a at 2007-7-12 2:00:25 > top of Java-index,Java Essentials,Java Programming...
# 7

> I heard If i Use CSV it will be easier to read students record into the Database table.

You still haven't stated what your problem is!!!

In order to use a CSV file you need to know how to read a line of text from a file. Do you know how to do this? If so, where is your posted code showing how you do this.

Then once you have a line of text, you need to parse the text into individual tokens. Do you know how to do this? Did you search the forum for examples of how to do this, since there are many examples posted.

Finally once you have individual tokens you can create an SQL statement to insert the data into the database. Do you know how to do this?

You need to learn how to break a problem down into individual steps and state which step you are having a problem with.

> Could you please give a Sample code to import CSV File into Database

We are not going to write the code for you and that statement does not tell us what you are having a problem with.

camickra at 2007-7-12 2:00:25 > top of Java-index,Java Essentials,Java Programming...
# 8

Basic rough out ...

import java.sql.*;

import java.io.*;

public class CSVDataImporter {

private [url http://java.sun.com/developer/JDCTechTips/2004/tt1201.html#1]Scanner csvScanner;[/url]

private [url http://java.sun.com/docs/books/tutorial/jdbc/index.html]Connection conn;[/url]

private PreparedStatement csvInsert;

public CSVDataImporter() {

/* ... */

}

public void getConnection(String uid, String pwd) {

try {

conn = ... ;

} catch(SQLException sqle) {

/* ... */

}

}

public void readAndInsert(String fName) {

String record,

partA,

partB,

partC;

try {

csvScanner = new Scanner(new File(fName));

while (csvScanner.hasNext()) {

/* get next record or token */

insertData(partA, partB, partC);

}

} catch(IOException ioe) {

/* ... */

}

}

public void insertData(String _partA, String _partB, String _partC) {

try {

} catch(SQLException sqle) {

/* ... */

}

}

}

abillconsla at 2007-7-12 2:00:25 > top of Java-index,Java Essentials,Java Programming...
# 9

Hi

I Learned how to read a file text and Parse as StringTokenizer. But still i don't know how to read the Individual tokens into to database.

But now i face a new Problem, i am not able to sort it out.

i am posting my code

import java.io.FileReader;

import java.io.FileWriter;

import java.io.BufferedReader;

import java.io.PrintWriter;

import java.io.IOException;

import java.io.*;

import java.util.*;

public class CSVExample {

public static void main(String[] args) throws IOException {

BufferedReader inputStream = null;

PrintWriter outputStream = null;

try {

inputStream = new BufferedReader(new FileReader("file.csv"));

String text;

while((text=inputStream.readLine())!= null)

{

StringTokenizer st = new StringTokenizer(text);

if(st.hasMoreTokens())

{

System.out.println(st.nextToken());

}

}

} finally {

if (inputStream != null) {

inputStream.close();

}

}

}

}

Here the Problem is The file.csv has got two fields ID, NAME The content of this file is as follows

T12,MR.RAJ KUMAR

T13,MR.EARNEST DIES

T14,MR.MATHEW HYDEN

Now when i StringTokenize this File The Output printed as follows

T12,MR.RAJ

T13,MR.EARNEST

T14,MR.MATHEW

That means when it finds the Space it is not printing the Remaining Text.

Please Help me in this and then Tell me how to INSER The Tokens into the Database Table

Thank you for your service

Cheers

Jofin

jofin123a at 2007-7-12 2:00:26 > top of Java-index,Java Essentials,Java Programming...
# 10
Did what I posted help?
abillconsla at 2007-7-12 2:00:26 > top of Java-index,Java Essentials,Java Programming...
# 11

Hi abillconsl

I am not that much Experienced java programer. just now i am trying to Learn. What you posted will be Usefull I think. Because after seeing the Scanner in your Posted only. I started to Learn about it. More over if you give Little bit elaborately, I think it will be More Helpful, Since i am a Beginner.

Could you please give state any Command or Give some help on the Previouse Post what i have tried According to Mr.camickr's Suggestion, But still I don't know how to use the Tonkens into the SQL statement to insert into the Database table.

Please help me to Learn the things and implement them

Thank you for your service

Cheers

jofin

jofin123a at 2007-7-12 2:00:26 > top of Java-index,Java Essentials,Java Programming...
# 12

If you click on the hotlinks in the import statements it will take you to the tips/tutorials - there will be able to answer your questions better than I could. If you get stuck on any particular piece of code, whether in the tutorial/tip or your own, post that back and ask specific questions, such as ... "this line here - why does that dohicky need to have three arguments passed to it?" or something similar ... then we can help you.

abillconsla at 2007-7-12 2:00:26 > top of Java-index,Java Essentials,Java Programming...
# 13

> Hi

>

> I Learned how to read a file text and Parse

> as StringTokenizer. But still i don't know how to

> read the Individual tokens into to database.

>

> But now i face a new Problem, i am not able to sort

> it out.

>

> i am posting my code

Try this code - note the commented out and replaced code - it should do what you want.

import java.io.FileReader;

import java.io.FileWriter;

import java.io.BufferedReader;

import java.io.PrintWriter;

import java.io.IOException;

import java.io.*;

import java.util.*;

public class CSVExample {

public static void main(String[] args) throws IOException {

BufferedReader inputStream = null;

PrintWriter outputStream = null;

try {

inputStream = new BufferedReader(new FileReader("file.csv"));

String text;

String[] tokens;

while((text=inputStream.readLine())!= null)

{

// StringTokenizer st = new StringTokenizer(text);

tokens = text.split(",");

//if(st.hasMoreTokens())

for (int i = 0l i < tokens.length;i++)

{

System.out.println(tokens[i]);

}

}

} finally {

if (inputStream != null) {

inputStream.close();

}

}

}

}

Message was edited by:

abillconsl

abillconsla at 2007-7-12 2:00:26 > top of Java-index,Java Essentials,Java Programming...
# 14

> But still i don't know how to read the Individual tokens into to database.

Well, you need to create an SQL statement to insert the data into the database. Read the [url http://java.sun.com/docs/books/tutorial/]JDBC Database Access[/url] tutorial for the basics.

You would then use the tokens to create a PreparedStatement to execute the SQL:

http://forum.java.sun.com/thread.jspa?forumID=31&threadID=780871

> But now i face a new Problem,

Read the StringTokenizer API. If you don't specify a delimiter then is uses "," and " " as delimiters (as well as other characters). If you only want "," as a delimiter then you need to specify that.

camickra at 2007-7-12 2:00:26 > top of Java-index,Java Essentials,Java Programming...
# 15

Hi

I tried to that with your suggestion now i am getting a Error During the Run time.

My Code is This

import java.io.FileReader;

import java.io.FileWriter;

import java.io.BufferedReader;

import java.io.PrintWriter;

import java.io.IOException;

import java.io.*;

import java.util.*;

import java.sql.*;

public class CSVExample {

public static void main(String[] args) throws IOException {

BufferedReader inputStream = null;

PrintWriter outputStream = null;

Connection con=null;

ResultSet rs;

Statement st;

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:Library");

System.out.println("Connected");

}

catch(ClassNotFoundException ex)

{

ex.printStackTrace();

}

catch(SQLException e)

{

e.printStackTrace();

}

try {

inputStream = new BufferedReader(new FileReader("file.csv"));

String text;

while(true)

{

text = inputStream.readLine();

if(text==null)

{

break;

}

StringTokenizer token =new StringTokenizer(text,",");

System.out.println("LOOP BROKEN");

while(token.hasMoreTokens())

{

try

{

String id=token.nextToken();

String name =token.nextToken();

String age=token.nextToken();

//String count=token.nextToken();

//String cat=token.nextToken();

//System.out.println();

// SQL to insert the Tokens into the Database Table

String sql="INSERT INTO Member(ID,Name,Age)VALUES(?,?,?)";

PreparedStatement pstm=con.prepareStatement(sql);

pstm.setString(1,id);

pstm.setString(2,name);

pstm.setString(3,age);

pstm.executeUpdate();

pstm.close();

}

catch(SQLException ex)

{

ex.printStackTrace();

}

}

}

} finally {

if (inputStream != null) {

inputStream.close();

}

}

}

}

I think there Error is in this String id=token.nextToken();

String name =token.nextToken();

String age=token.nextToken();

Place only. But i am not able to Findout out what would be the Reason to get the Error.

The Acuall Error is this Exception in thread "main" java.util.NoSuchElementException

Please provide me a Solution to come out of this Problem

Thank you for your service

Cheers

Jofin

jofin123a at 2007-7-21 20:19:56 > top of Java-index,Java Essentials,Java Programming...
# 16
You certainly didn't appear to try the code I posted.
abillconsla at 2007-7-21 20:19:56 > top of Java-index,Java Essentials,Java Programming...
# 17

Did you read the API to find out how the nextToken() method works. Thats what the API is for. It will explain why the exception is thrown.

> The file.csv has got two fields ID, NAME

Well then why are you trying to access "THREE" tokens?

> String id=token.nextToken();

> String name =token.nextToken();

> String age=token.nextToken();

camickra at 2007-7-21 20:19:56 > top of Java-index,Java Essentials,Java Programming...
# 18

Hi Friends

With your help i have done something that works fine for me. Now i am posting the Code here. Please have look at it and Give your comments over that.

But i have not used StringTokenizer

My code is this

import java.io.*;

import java.util.*;

import java.sql.*;

public class ImportStudent

{

BufferedReader inputStream = null;

PrintWriter outputStream = null;

Connection con=null;

ResultSet rs;

Statement st;

String[] str;

public ImportStudent(Connection con)throws IOException

{

try

{

String result;

PreparedStatement pstm = con.prepareStatement("insert into student (ID,NAME,ENTRY,LIMITE,CATE)values(?,?,?,?,?)");

inputStream = new BufferedReader(new FileReader("file.csv"));

while((result=inputStream.readLine())!=null)

{

str=result.split(",");

for(int i=0;i<5;i++)

{

pstm.setString((i+1),str[i]);

//System.out.println(str[i]);

}

pstm.addBatch();

//pstm.executeUpdate();

}

pstm.executeBatch();

System.out.println("COMPLEEEEEEEEEEEEEETEEEEEEEEEEETEE");

}

catch(SQLException ex)

{

}

catch(FileNotFoundException ex)

{

}

}

}

Please post your comment on this code and also tell me whether speed of this importing will be ok or not. For me it take 5 to 8 Second to import the Data.

Thank you for your Help

Cheers

Jofin

jofin123a at 2007-7-21 20:19:56 > top of Java-index,Java Essentials,Java Programming...
# 19

Two things:

1) This line: for(int i=0;i<5;i++)

Should be:

for(int i=0;i<str.length;i++)

2) Don't like the way you spelled COMPLETETE(SIC)

~Bill>

abillconsla at 2007-7-21 20:19:56 > top of Java-index,Java Essentials,Java Programming...
# 20

hi Thank you very much.

one more thing i wanted to ask. from the CSV File i read the Data. in that CSV File there are 5 Fields among those two the Last two field are Integer. Now in the database table also there are Five Fields, the last two fileds are Integer. now i want to indentify the Integer form the text i read from the CSV file and Store it in the Database

Please help me out to come out of this Issue

Thank you for your service

Cheers

Jofin

jofin123a at 2007-7-21 20:19:56 > top of Java-index,Java Essentials,Java Programming...
# 21
Read the Integer API. There is a method that will convert a numeric String to an Integer.
camickra at 2007-7-21 20:19:56 > top of Java-index,Java Essentials,Java Programming...
# 22

Another option is to let the DB to it for you. For example, in Oracle there is the to_number function:

insert into tableX

(tableX.id, tableX.name, tableX.amt)

values

(_id, _name, to_number(_amt)

... But that's not a Java question, and I do not know what DB you are working with.

abillconsla at 2007-7-21 20:19:56 > top of Java-index,Java Essentials,Java Programming...
# 23

Hi

I tried to convert the String into Integer by using Integer.parseInt()

method.

But when i execute the PreparedStatement i am getting General Error

I post the Code only where i am doing the Convertion

Please help me out

pstm = conn.prepareStatement("insert into Members (RollNumber,Name,Mstart,Bcnt,Mcat)values(?,?,?,?,?)");

System.out.println("This this the DATABASE CONNECTION:"+conn);

String result;

System.out.println("YES I AM CALLED FOR HELP");

String FilePath=txtLocation.getText();

inputStream = new BufferedReader(new FileReader(FilePath));

while((result=inputStream.readLine())!=null)

{

StringTokenizer stk = new StringTokenizer(result,",");

String studentid=stk.nextToken();

pstm.setString(1,studentid);

String studentname =stk.nextToken();

pstm.setString(2,studentname);

String entrydate=stk.nextToken();

pstm.setString(3,entrydate);

int bcount =Integer.parseInt(stk.nextToken());

pstm.setInt(4,bcount);

int cate =Integer.parseInt(stk.nextToken());

pstm.setInt(5,cate);

pstm.executeUpdate();

}

It gives this general Error in this line pstm.executeUpdate

Please tell me what would be the Problem here.

Thank you for you help

Cheers

Jofin

jofin123a at 2007-7-21 20:19:56 > top of Java-index,Java Essentials,Java Programming...
# 24

I'd wrap the Integer.parseInt calls in try { } catch(NumberFormatException nfe) { System.out.println(nfe); }

and show a message when caught.

But more troubling is the 'General Error' thing you are talking about. So you need to wrap your SQL calls in try/catch statements and your I/O in try/catch statements as well.

abillconsla at 2007-7-21 20:19:56 > top of Java-index,Java Essentials,Java Programming...