I have to read records from CSV file and store them in Mysql database.
I know about "LOAD DATA INFILE" but in my case I have to get single record from file, check if it is in valid format/length etc and then store it in database.
// list to store records from CSV file
ArrayList<String> list = new ArrayList<String>();
//Read one line at a time
while ((nextLine = reader.readNext()) != null)
{
for (String number : nextLine)
{
if (number.length() > 12 && number.startsWith("88"))
{
list.add(number);
} else if (number.length() > 9 && number.startsWith("54"))
{
list.add(number);
}
else if (number.length() > 8 && number.startsWith("99"))
{
list.add(number);
}
else
{
// ....
}
// method to insert data in database
insertInToDatabase(list);
}
}
and method to insert record in db: taken from here
private void insertInToDatabase(ArrayList<String> list)
{
try
{
String query = "INSERT INTO mytable(numbers) VALUES(?)";
prepStm = conn.prepareStatement(query);
for (String test : list)
{
prepStm.setString(1, test);
prepStm.addBatch();// add to batch
prepStm.clearParameters();
}
prepStm.executeBatch();
}
}
This is working, but the rate at which the records are inserting is very slow. is there any way by which I can insert records faster.