Thursday, December 16, 2004

Parsing CSV files in 5 minutes or less!

CsvJdbc - a JDBC driver for CSV files Rocks!

I was looking for an utility which can read and parse the CSV files. The open source utility CsvJdbc was perfect for my requirements. It parses the given CSV file with no problem. Just include the csvjdbc.jar in the classpath and start using the API. The command line argument is C:\\test (Java requires the escape character \ for the \, which is the separator). The filename is anything.csv and is stored in the directory specified above. Version is Version 0.10.
The documentation says :
The driver also now supports scrollable result sets.
This following example code shows how these are used.
...

Connection conn = Drivermanager.getConnection("jdbc:relique:csv:" + args[0],props)

Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 0);

ResultSet results = stmt.executeQuery("SELECT ID,NAME FROM sample");

resulst.next();
...
results.first();
...
results.previous();
...
results.relative(2);
...
results.absolute(2);
...
But it looks like it is not implemented yet. I got : Oops-> java.lang.UnsupportedOperationException: ResultSet.relative() unsupported error message.

Here is the modified example program that I am using for my purposes:

/*
* Created on Dec 16, 2004
* @author BXParanj
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class RegistrationParser {
private String userName;
private String password;

public RegistrationParser(String fileName) {

}

public static void main(String[] args) {

String index = "fcgp001";
try
{
// load the driver into memory
Class.forName("org.relique.jdbc.csv.CsvDriver");

// create a connection. The first command line parameter is assumed to
// be the directory in which the .csv files are held
Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + args[0] );

// create a Statement object to execute the query with
Statement stmt = conn.createStatement();

// Select the EBK_USERNAME and EBK_PASSWORD columns from lead.csv file

String sqlQuery = "SELECT EBK_USERNAME, EBK_PASSWORD FROM lead WHERE EBK_USERNAME =" + index ;
ResultSet results = stmt.executeQuery(sqlQuery);

// dump out the results
while (results.next())
{
System.out.println("EBK_USERNAME= " + results.getString("EBK_USERNAME") + " EBK_PASSWORD= " + results.getString("EBK_PASSWORD"));
}

// clean up
results.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println("Oops-> " + e);
}
}
}

No comments:

Post a Comment