- Converting Strings to int and int to String
- Append text to file in Java
- Get name of current method in Java
- Convert String to Date in Java
- Connecting to Oracle using Java JDBC
- Convert Java util.Date to sql.Date
- Java Fast File Copy using NIO
- Create Thumbnail of an image in Java
- Creating JSON data in Java
- PDF Generation in Java using iText
- HTTP Proxy setting in Java
- Java Singleton example
- Capture screen shots in Java
- Files-Directory listing in Java
- Creating ZIP and JAR Files in Java
- Parsing / Reading XML file in Java
- Convert Array to Map in Java
- Send Email using Java
- Send HTTP request & fetching data using Java
- Resize an Array in Java
[Java Best Practice:10 Most Useful Java Best Practice Quotes for Java Developers](http://viralpatel.net/blogs/most-useful-
java-best-practice-quotes-java-developers/)
- Quote 1: Avoid creating unnecessary objects and always prefer to do Lazy Initialization
- Quote 2: Never make an instance fields of class public
- Quote 3: Always try to minimize Mutability of a class
- Quote 4: Try to prefer Interfaces instead of Abstract classes
- Quote 5: Always try to limit the scope of Local variable
- Quote 6: Try to use standard library instead of writing your own from scratch
- Quote 7: Wherever possible try to use Primitive types instead of Wrapper classes
- Quote 8: Use Strings with utmost care.
- Quote 9: Always return empty Collections and Arrays instead of null
- Quote 10: Defensive copies are savior
employee.csv β Sample CSV file:
EMPLOYEE_ID,FIRSTNAME,LASTNAME,BIRTHDATE,SALARY
1,Dean,Winchester,27.03.1975,60000
2,John,Winchester,01.05.1960,120000
3,Sam,Winchester,04.01.1980,56000
Table: Customer β Database table
CREATE TABLE Customer (
EMPLOYEE_ID NUMBER,
FIRSTNAME VARCHAR2(50 BYTE),
LASTNAME VARCHAR2(50 BYTE),
BIRTHDATE DATE,
SALARY NUMBER
)
Main.java β Load sample.csv to database
package net.viralpatel.java;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
private static String JDBC_CONNECTION_URL =
"jdbc:oracle:thin:SCOTT/TIGER@localhost:1500:MyDB";
public static void main(String[] args) {
try {
CSVLoader loader = new CSVLoader(getCon());
loader.loadCSV("C:\\employee.sql", "CUSTOMER", true);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Connection getCon() {
Connection connection = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(JDBC_CONNECTION_URL);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
CSVLoader.java β Utility class to load CSV into Database
package net.viralpatel.java;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import au.com.bytecode.opencsv.CSVReader;
/**
*
* @author viralpatel.net
*
*/
public class CSVLoader {
private static final
String SQL_INSERT = "INSERT INTO ${table}(${keys}) VALUES(${values})";
private static final String TABLE_REGEX = "\\$\\{table\\}";
private static final String KEYS_REGEX = "\\$\\{keys\\}";
private static final String VALUES_REGEX = "\\$\\{values\\}";
private Connection connection;
private char seprator;
/**
* Public constructor to build CSVLoader object with
* Connection details. The connection is closed on success
* or failure.
* @param connection
*/
public CSVLoader(Connection connection) {
this.connection = connection;
//Set default separator
this.seprator = ',';
}
/**
* Parse CSV file using OpenCSV library and load in
* given database table.
* @param csvFile Input CSV file
* @param tableName Database table name to import data
* @param truncateBeforeLoad Truncate the table before inserting
* new records.
* @throws Exception
*/
public void loadCSV(String csvFile, String tableName,
boolean truncateBeforeLoad) throws Exception {
CSVReader csvReader = null;
if(null == this.connection) {
throw new Exception("Not a valid connection.");
}
try {
csvReader = new CSVReader(new FileReader(csvFile), this.seprator);
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Error occured while executing file. "
+ e.getMessage());
}
String[] headerRow = csvReader.readNext();
if (null == headerRow) {
throw new FileNotFoundException(
"No columns defined in given CSV file." +
"Please check the CSV file format.");
}
String questionmarks = StringUtils.repeat("?,", headerRow.length);
questionmarks = (String) questionmarks.subSequence(0, questionmarks
.length() - 1);
String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
query = query
.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ","));
query = query.replaceFirst(VALUES_REGEX, questionmarks);
System.out.println("Query: " + query);
String[] nextLine;
Connection con = null;
PreparedStatement ps = null;
try {
con = this.connection;
con.setAutoCommit(false);
ps = con.prepareStatement(query);
if(truncateBeforeLoad) {
//delete data from table before loading csv
con.createStatement().execute("DELETE FROM " + tableName);
}
final int batchSize = 1000;
int count = 0;
Date date = null;
while ((nextLine = csvReader.readNext()) != null) {
if (null != nextLine) {
int index = 1;
for (String string : nextLine) {
date = DateUtil.convertToDate(string);
if (null != date) {
ps.setDate(index++, new java.sql.Date(date
.getTime()));
} else {
ps.setString(index++, string);
}
}
ps.addBatch();
}
if (++count % batchSize == 0) {
ps.executeBatch();
}
}
ps.executeBatch(); // insert remaining records
con.commit();
} catch (Exception e) {
con.rollback();
e.printStackTrace();
throw new Exception(
"Error occured while loading data from file to database."
+ e.getMessage());
} finally {
if (null != ps)
ps.close();
if (null != con)
con.close();
csvReader.close();
}
}
public char getSeprator() {
return seprator;
}
public void setSeprator(char seprator) {
this.seprator = seprator;
}
}
Usage
CSVLoader loader = new CSVLoader(connection);
loader.loadCSV("C:\\employee.csv", "TABLE_NAME", true);
Load file with semicolon as delimeter:
CSVLoader loader = new CSVLoader(connection);
loader.setSeparator(';');
loader.loadCSV("C:\\employee.csv", "TABLE_NAME", true);
Load file without truncating the table:
CSVLoader loader = new CSVLoader(connection);
loader.loadCSV("C:\\employee.csv", "TABLE_NAME", false);