csv output using spring-jdbctemplate during fetching multiple rows

空扰寡人 提交于 2019-12-11 06:48:36

问题


I am using spring jdbctemplate to interact with Oracle database. For fetching multiple rows for a given condition, I want to store the result in a csv file having Column names as the header.

I tried few ways -

List<Bean> list = jdbcTemplate.query('query','parameters',customizedrowmapper);

In customizedrowmapper, I am fetching the rows from result set and setting the fields in Bean class. I could not find any easy way to convert from bean to csv file. As I dont have access to bean class code.

2nd way I found was to writer ResultSet directly to csv file like below using opencsv library.

CSVWriter wr = new CSVWriter(new FileWriter("Report.csv"), ','); wr.writeAll(rs, true); wr.flush(); wr.close();

This is working okay, but it is skipping one row while writing to csv. I tried few queries. Manually, I can see 4 rows in the result, but in the CSV, it stores only three rows. Anyone faced a similar issue?

Or any other way we can achieve the same, without manually getting each record from ResultSet and making it comma-separated string and storing in file.


回答1:


Note that when jdbcTemplate passes a ResultSet to your RowCallbackHandler or Mapper, it has been already positioned at the first record (rs.next() was been called). CSVWriter calls rs.next() again before process any record, so first record never will be written. You need to write your data by yourself doing something like:

    public class CustomRowCallbackHandler implements RowCallbackHandler {
    @Override
    public void processRow(ResultSet rs) throws SQLException {
        try {
            CSVWriter w = new CSVWriter(new FileWriter("Report.csv"), ',');
            int columnCount = rs.getMetaData().getColumnCount();
            //Write column names
            String[] ssn = new String[columnCount];
            for(int i = 1; i < columnCount; i++){
                ssn[i - 1] = rs.getMetaData().getColumnName(i);
            }
            w.writeNext(ssn);
            //Write data
            do{
                String[] ss = new String[columnCount];
                for(int i = 1; i < columnCount; i++){
                    ss[i - 1] = rs.getString(i);
                }
                w.writeNext(ss);
            }while(rs.next());
            w.flush();
            w.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Hope it helps.



来源:https://stackoverflow.com/questions/39909715/csv-output-using-spring-jdbctemplate-during-fetching-multiple-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!