我正在使用Java将查询从数据库写入CSV文件。我该怎么做才能循环查询结果,以便在CSV文件中逐行显示。以下是我的代码片段。
StringBuilder sb = new StringBuilder();
sb.append(reportBO.projectList(this.getSearchBean());
sb,append(',');
sb.append('\n');
假设我的查询是
SELECT * FROM PROJECT
答案 0 :(得分:1)
如下所述循环结果集并将其写入文件
while (rs.next()){
sb.append(rs.getString(<ColumnName1>));
sb.append(',');
sb.append(rs.getString(<ColumnName2>));
sb.append(',');
sb.append(rs.getString(<ColumnName3>));
sb.append('\n');
}
如果要将数据填充到StringBuffer
中,请确保以固定间隔(例如,每1000行)将其写入文件。否则,如果结果包含大量行,则可能会获得OutOfMemoryException
。
答案 1 :(得分:0)
您需要CSV编写器才能正确处理此问题。值可以包含逗号,引号,换行符,并且必须正确转义。
从您的代码中,您似乎正在尝试编写bean而不是直接从ResultSet中获取内容。在这种情况下,您可以尝试univocity-parsers:
//creates a configuration object that allows you to determine how to
//format your CSV output, among many other things. Check the tutorial.
CsvWriterSettings settings = new CsvWriterSettings();
//Configures the parser to process input objects using the BeanWriterProcessor.
//This reads the data from your java beans. In this case the type is "TestBean"
//but in yours it seems that would be something like "SearchBean".
settings.setRowWriterProcessor(new BeanWriterProcessor<TestBean>(TestBean.class));
//Defines the headers to print out to the output. My "TestBean" class has the
//following fields. Adjust this to reflect the fields in your "SearchBean"
settings.setHeaders("amount", "pending", "date", "quantity", "comments");
// Creates a CsvWriter with the settings above
CsvWriter writer = new CsvWriter(new FileWriter(new File("/path/to/file.csv")), settings);
//Loads the beans from the database.
//The "loadBeanList" method is something you should implement.
List<TestBean> beansToPersist = loadBeanList();
//With a list of beans loaded from the database, you can simply call this
//and write everything into your CSV file. You can also write beans one by one.
writer.processRecordsAndClose(beansToPersist);
披露:我是这个图书馆的作者。它是开源和免费的(Apache V2.0许可证)。
答案 2 :(得分:0)
以下是我解决方案的方法。希望它可以帮助某人。谢谢大家的帮助......
for (int i = 0; i < ((List<BaseDTOInf>) getProjectList(searchBean)).size();i++) {
BaseDTO list = (BaseDTO) getProjectList(searchBean).get(i);
list.getDataMap().get("A");
list.getDataMap().get("B");
list.getDataMap().get("C");
list.getDataMap().get("D");
list.getDataMap().get("E");
list.getDataMap().get("F");
sb.append(list.getDataMap().get("A"));
sb.append(',');
sb.append(list.getDataMap().get("B"));
sb.append(',');
sb.append(list.getDataMap().get("C"));
sb.append(',');
sb.append(list.getDataMap().get("D"));
sb.append(',');
sb.append(list.getDataMap().get("E"));
sb.append(',');
sb.append('\n');
}