| 34769 |
vikas.jang |
1 |
package com.spice.profitmandi.common.util;
|
|
|
2 |
|
|
|
3 |
import org.springframework.beans.factory.annotation.Value;
|
|
|
4 |
|
|
|
5 |
import java.io.File;
|
|
|
6 |
import java.nio.file.*;
|
|
|
7 |
import java.sql.*;
|
|
|
8 |
|
|
|
9 |
public class CsvUtil {
|
|
|
10 |
|
|
|
11 |
private CsvUtil() {
|
|
|
12 |
}
|
|
|
13 |
|
|
|
14 |
private static final String username = "root";
|
|
|
15 |
private static final String password = "shop2020";
|
|
|
16 |
|
|
|
17 |
public static File generateCsvFromQuery(String jdbcUrl, String query, String headers) throws Exception {
|
|
|
18 |
Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
|
|
|
19 |
PreparedStatement stmt = conn.prepareStatement(query);
|
|
|
20 |
ResultSet rs = stmt.executeQuery();
|
|
|
21 |
|
|
|
22 |
ResultSetMetaData metaData = rs.getMetaData();
|
|
|
23 |
int columnCount = metaData.getColumnCount();
|
|
|
24 |
|
|
|
25 |
StringBuilder csvBuilder = new StringBuilder();
|
|
|
26 |
|
|
|
27 |
// Headers
|
|
|
28 |
if (headers != null && !headers.trim().isEmpty()) {
|
|
|
29 |
csvBuilder.append(headers.trim()).append("\n");
|
|
|
30 |
} else {
|
|
|
31 |
for (int i = 1; i <= columnCount; i++) {
|
|
|
32 |
csvBuilder.append(metaData.getColumnLabel(i));
|
|
|
33 |
if (i < columnCount) csvBuilder.append(",");
|
|
|
34 |
}
|
|
|
35 |
csvBuilder.append("\n");
|
|
|
36 |
}
|
|
|
37 |
|
|
|
38 |
// Rows
|
|
|
39 |
while (rs.next()) {
|
|
|
40 |
for (int i = 1; i <= columnCount; i++) {
|
|
|
41 |
String value = rs.getString(i);
|
|
|
42 |
csvBuilder.append(value != null ? value.replaceAll(",", " ") : "");
|
|
|
43 |
if (i < columnCount) csvBuilder.append(",");
|
|
|
44 |
}
|
|
|
45 |
csvBuilder.append("\n");
|
|
|
46 |
}
|
|
|
47 |
|
|
|
48 |
rs.close();
|
|
|
49 |
stmt.close();
|
|
|
50 |
conn.close();
|
|
|
51 |
|
|
|
52 |
Path tempFile = Files.createTempFile("query-result-", ".csv");
|
|
|
53 |
Files.write(tempFile, csvBuilder.toString().getBytes());
|
|
|
54 |
return tempFile.toFile();
|
|
|
55 |
}
|
|
|
56 |
}
|
|
|
57 |
|