我正在尝试将 ResultSet 对象转换为 CSV 格式的 String 对象。我尝试使用 OpenCV 将其转换为 CSV 文件,但我需要将其作为字符串。有一个选项可以先将其转换为文件,然后将数据转换为字符串,然后删除文件,但这将是我无法承受的额外开销。
有没有办法实现它,我尝试搜索但到目前为止还没有任何东西。
或者,您可以使用CSVPrinter来自Apache Commons CSV 的。
CSVPrinter::printRecords( ResultSet )该方法CSVPrinter::printRecords接受一个ResultSet参数。
请参阅csvPrinter.printRecords(resultSet);以下示例代码中的关键行。
package org.myorg;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class QueryToCSV {
public static void main(String[] args) throws IOException {
if ( args.length < 2)
throw new IllegalArgumentException("Usage: QueryToCSV.jar <JDBCConnectionURL> <SQLForQuery> -> output to STDOUT and STDERR");
// Create a variable for the connection string.
String connectionUrl = args[0];
String sqlQuery = args[1];
try ( Connection conn = DriverManager.getConnection(connectionUrl); ) {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
try (Statement st = conn.createStatement();) {
ResultSet resultSet = st.executeQuery(sqlQuery);
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(resultSet));
csvPrinter.printRecords(resultSet);
csvPrinter.close();
}
}
catch (SQLException e) {
e.printStackTrace();
System.exit(1);
}
catch (IllegalArgumentException ie) {
System.err.println(ie.getMessage());
System.exit(1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
不要编写自己的方法,CSV 不仅仅是用逗号连接的字符串。有几个关于配额、转义等的问题。使用专用库。就我个人而言,我更喜欢使用 univocity-parsers 来处理“损坏的”csv 文件,但如果您处理 ResultSet,则可以使用 opencsv 库。
StringWriter stringWriter = new StringWriter();
CSVWriter csvWriter = new CSVWriter(stringWriter);
csvWriter.writeAll(resultSet, true); // including column names
String result = stringWriter.toString();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3316 次 |
| 最近记录: |