Reputation: 71
I have a function that connects to a database, executes a sql query and tries to write the result into a file.
public class DBReader {
public ResultSet executeSQL(SqlContainer sc) {
String url = "url";
String user = "user";
String password = "pw";
Connection con;
Statement stmt;
ResultSet rs;
try {
System.out.println("=== Started SQL ===");
Class.forName("com.ibm.db2.jcc.DB2Driver");
con = DriverManager.getConnection(url, user, password);
con.setAutoCommit(false);
stmt = con.createStatement();
rs = stmt.executeQuery(sc.getSQL());
CSVWriter writer = new CSVWriter(new FileWriter("result.csv"));
writer.writeAll(rs, true);
stmt.close();
con.commit();
con.close();
System.out.println(" Finished SQL");
return rs;
} catch (SQLException | ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return null;
}
}
Yet when I execute above function the file that comes out is empty. I've used following code to test if the result set is empty but if I execute:
while (rs.next()) {
String value = rs.getString(4);
System.out.println("Something = " + value);
}
it returns some values.
I'd apreaciate any help or nods in the right direction, thanks in advance.
Upvotes: 2
Views: 2863
Reputation: 1056
You should close the writer
as well:
writer.close();
Or better, you can use the try-with-resource statement which closes it automatically:
try(CSVWriter writer = new CSVWriter(new FileWriter("result.csv"));) {
System.out.println("=== Started SQL ===");
Class.forName("com.ibm.db2.jcc.DB2Driver");
con = DriverManager.getConnection(url, user, password);
con.setAutoCommit(false);
stmt = con.createStatement();
rs = stmt.executeQuery(sc.getSQL());
writer.writeAll(rs, true);
stmt.close();
con.commit();
con.close();
System.out.println(" Finished SQL");
return rs;
} catch (SQLException | ClassNotFoundException | IOException e) {
e.printStackTrace();
}
Upvotes: 5