Stelios Stelios - 5 months ago 38
Java Question

parsing timestamp from mysql to csv using java

i have a mysql db, and i have one table which has many columns including a timestamp one. i want to read the table and write it to a csv file. then i will read from the csv file the data and insert it in another db and table. all these are done through java.
I can read the table date and the timestamp from the first db, but the timestap is not written correctly into the csv file.. only the last few digits are written. for example if i have a timestamp 2012-11-01 02:18:00.0 only the 18:00.0 will be written to the csv. All the other stuff work fine. For example if i hard write a timestamp i can write it to the second db. there;s the code for reading mysql and writing to csv :

con = DriverManager.getConnection("jdbc:mysql://localhost/campdb", "...", "...");

stmt = (Statement) con.createStatement();
fw = new FileWriter(filename);
PrintWriter a = new PrintWriter(fw);
ResultSet res = stmt.executeQuery("SELECT * FROM CAMPREQ;");
while (res.next())
{
String ID = res.getString(1);
java.sql.Date date = res.getDate(2);
//java.util.Date jdate = new java.util.Date(date.getTime());
String company = res.getString(3);
String time = res.getString(4);
String origin = res.getString(5);
String dest = res.getString(6);
String timestamp = res.getString(7);
System.out.println(timestamp);
a.print(ID);
a.print(',');
a.print(date);
a.print(',');
a.print(company);
a.print(',');
a.print(time);
a.print(',');
a.print(origin);
a.print(',');
a.print(dest);
a.print(',');
a.print(timestamp);
a.print('\n');
a.flush();

}


The System.out command prints the timestamp as it should be written, however it is not written correctly in the csv :(
thank you

Answer

try using the code below, it works for most databases and properly takes all datatypes correctly with correct formatting. This should solve your problem not just for mysql but for any other database

 public static StringBuffer resultSetToStringCsv(ResultSet resultSet) throws Exception{
StringBuffer stringwriter = new StringBuffer();

ResultSet rs = resultSet;
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();

//Write column names
for(int i=1;i<=numberOfColumns;i++){
 stringwriter.append(rsmd.getColumnName(i));
 stringwriter.append(',');
}
stringwriter.append('\n');
//Write rows
while(rs.next()){
 for(int i=1;i<=numberOfColumns;i++){
  try{
   stringwriter.append(""+rs.getObject(i));
  stringwriter.append(',');
  }catch (Exception e) {
   stringwriter.append("null");
 stringwriter.append(',');
}
}    
 stringwriter.append('\n');
}

You can check http://bmukorera.blogspot.com/2012/11/resultset-query-to-string-generating.html for full code

Comments