我需要将结果集转换为csv用于任何数据库(不仅仅是postgres)
使用opencsv时正在创建空csv文件。
这里是servlet中doGet方法的代码:
final String JDBC_DRIVER = "org.postgresql.Driver";
final String DB_URL = "jdbc:postgresql://localhost:5432/postgres";
// Database credentials
final String USER = "postgres";
final String PASS = "12345";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n");
PreparedStatement ps = null;
Connection conn = null;
try {
// Register JDBC driver
Class.forName("org.postgresql.Driver");
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
//stmt = conn.createStatement();
String sql = "SELECT * FROM users";
ps = conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery();
/*if(rs.next()){
System.out.println("Name = "+rs.getString("first_name"));
}*/ //prints name so rs is not empty
//rs.first();
CSVWriter writer = new CSVWriter(new FileWriter("Test.csv"));
//even tried with seperator '\t' or ','
writer.writeAll(rs, true);
writer.close();
out.println("</body></html>");
// Clean-up environment
rs.close();
ps.close();
conn.close();
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (ps != null)
ps.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
} //end try
不确定错误是什么。尝试了不同的方式,但csv总是空的。
甚至尝试过writer.flush(),rs.beforeFirst(),rs.first()也没有用。
答案 0 :(得分:0)
你的问题是你没有在html中看到数据 - 如果是这种情况,那么在CSVWriter中创建一个新的FileWriter而不是传递你的变量。
或者是您检查了Test.csv和文件,没有任何内容?如果是这样,那么首先通过在executeQuery之后添加以下内容来检查结果集中是否确实存在数据:
rs.last();
long numberOfRecords = rs.getRow();
rs.beforeFirst();
System.out.println("Number of Users in table is: " + numberOfRecords);