Storing multiple .csv files into database table in liunx

Joined
Jul 1, 2012
Messages
6
Reaction score
0
here is the code ,I want to store all lines of .csv files into database table But i am able to store only one line from each .csv file so any one suggest me.


package org.Example;

import java.awt.List;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;

public class automateImport {
public static void main(String[] args) {

DBase db = new DBase();
Connection conn = db.connect("jdbc:mysql://localhost:3306/database name",
"username", "pwd");
db.importData(conn);

}
}
class DBase {
public ArrayList<String> lstFiles;

public DBase() {
lstFiles = new ArrayList<String>();
// printFnames("folder name");
GetAllDirectories("folder name");
}

public Connection connect(String db_connect_str, String db_userid,
String db_password) {
Connection conn;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();

conn = DriverManager.getConnection(db_connect_str, db_userid,
db_password);

} catch (Exception e) {
e.printStackTrace();
conn = null;
}

return conn;
}

public void printFnames(String sDir) {
File[] faFiles = new File(sDir).listFiles();
for (File file : faFiles) {
if (file.getName().endsWith(".csv")) {
lstFiles.add(file.getAbsolutePath());
}
}
}

public void GetAllDirectories(String sDir) {

File[] faFiles = new File(sDir).listFiles();
for (File file : faFiles) {
if (file.isDirectory()) {
// lstDirs.add(file.getAbsolutePath());
if (file.getName().endsWith("output_dir")) {
printFnames(file.getAbsolutePath());
}
GetAllDirectories(file.getAbsolutePath());
}
}
}

public void importData(Connection conn) {
Statement stmt;
String query;

try {
Iterator<String> iterator = lstFiles.iterator();
while (iterator.hasNext()) {

stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);

query = "LOAD DATA LOCAL INFILE '"
+ iterator.next()
+ "' INTO TABLE table1 FIELDS TERMINATED BY ',' ENCLOSED BY '' LINES TERMINATED BY '\r\n'(fields name);";

stmt.executeUpdate(query);
System.out.println(iterator.next());
}

} catch (Exception e) {
e.printStackTrace();
stmt = null;
}
}
};
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top