I am very new to Java. I have a task with two steps.
- I want to read all data from a
.csvfile. - After reading that data I have to put it into a SQL Server database.
I have done step one. I’m able to read the .csv file data, but I don’t know that how to insert it into a database.
Here’s my code for fetching the .csv file data:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class DBcvsdataextractor {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String fileName="D:/USPresident Wikipedia URLs Thumbs HS.csv";
try {
BufferedReader br = new BufferedReader( new FileReader(fileName));
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
while( (fileName = br.readLine()) != null)
{
if(lineNumber++ == 0)
continue;
//break comma separated line using ","
st = new StringTokenizer(fileName, ",");
while(st.hasMoreTokens())
{
//display csv values
tokenNumber++;
System.out.print(st.nextToken() + '\t');
}
//new line
System.out.println(" ");
//reset token number
tokenNumber = 0;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now, how do I insert that data into SQL Server?
If you really want to do this with Java, and really want to write your own CSV parser as you currently did, you can
ArrayListfor each column in the CSV file, and populate those while reading the CSV fileArrayListinstances again to construct one bigINSERTstatement for all data, or oneINSERTstatement for each row you encountered in the CSV file. If you would opt for the last option, it is not even necessary to use thoseArrayListinstances. In that case you could construct an indiviualINSERTstatement while reading the CSV file, and submit it to the DB after each time a row has been read.I know the approach of constructing your query while reading the CSV file would be possible as well if you want to go for one big
INSERTstatement, but separating theINSERTfrom the reading of the CSV file has the big advantage you can replace your own CSV parser later on by a standard one without too much trouble.