- How to batch update or insert in data base
- Download opencsv-2.2.jar
package com.kartik.pdf; import java.io.*; import au.com.bytecode.opencsv.CSVReader; import java.util.*; import java.sql.*; public class BulkDataInsertCSVtoDataBase { public static void main(String[] args) throws Exception{ /* Create Connection objects */ Class.forName ("oracle.jdbc.OracleDriver"); Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/demo", "kartik", "kartik"); PreparedStatement stmt = null; String sql = "insert into employee (name, city, phone) values (?, ?, ?)"; stmt = conn.prepareStatement(sql); /* Read CSV file in OpenCSV */ String inputCSVFile = "inputCSVData.csv"; CSVReader reader = new CSVReader(new FileReader(inputCSVFile)); String [] nextLine; final int batchSize = 100; int count = 0; int successCount = 0; int failCount = 0; int notAavailable = 0; while ((nextLine = reader.readNext()) != null) { stmt.setString(1, nextLine[0]); stmt.setString(2, nextLine[1]); stmt.setInt(3,Integer.parseInt(nextLine[2])); // Add the record to batch stmt.addBatch(); try { if(++count % batchSize == 0) { int[] totalRecords = stmt.executeBatch(); } } catch(BatchUpdateException e) { //you should handle exception for failed records here totalRecords = e.getUpdateCounts(); for (int i = 0; i < totalRecords.length; i++) { if (totalRecords[i] >= 0) { successCount++; } else if (totalRecords[i] == Statement.SUCCESS_NO_INFO) { notAavailable++; } else if (totalRecords[i] == Statement.EXECUTE_FAILED) { failCount++; } } } } /* Close prepared statement */ stmt.close(); /* COMMIT transaction */ conn.commit(); /* Close connection */ conn.close(); } }