I want to export the result set of the SQL query to a CSV file. I am using opencsv to export to CSV file. I am using below code to achieve it.
ResultSet rs = statement.executeQuery(queryString); CSVWriter writer = new CSVWriter(new fileWriter "testFile.csv"), '|',CSVWriter.NO_QUOTE_CHARACTER); writer.writeAll(rs, true);
But the problem I face is, it automatically exports to the datatype of the database column which is from resultset.
Example: if I a column with datatype as float in datatype in CSV file I see as 100.00 and for another column I see value as 2.041928E+8 for 204192800.
But I want to CSV file to export to string type. The value as it as in the database.
How can I export the resulttype to CSV file with string datatype using opencsv?
Advertisement
Answer
And Another solution is, create your custom ResultSet Wrapper with your real resultset (source) and call
Also, you can create your custom ResultSetMetaData Wrapper to response ColumnType has String.
writer.writeAll(new MyResultSet(rs), true); //Wrapper class public class MyResultSet implements Resultset{ public MyResultSet(Resultset source, Map<String, NumberFormat > formatters){ //setting constructor properties and you can read here SQL resultset Metadata to complete formatters } //.... you will implement all sql.Resultset methods //example to implements public String getString(String columnName){ return formatters.get(columnName).format(source.getInt(columnName)); } public ResultSetMetaData getMetaData(){ return new MyResultSetMetaData(source); } } } // public MyResultSetMetaData implements ResultSetMetaData{ //will implement all ResultSetMetaData methods, //replace Numeric to String the column Type, then the value has retrieved by getString(column) public int getColumnType(int columnIndex){ return Types.VARCHAR;
}
}