forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenCSVDatabaseEx.java
More file actions
43 lines (33 loc) · 1.36 KB
/
OpenCSVDatabaseEx.java
File metadata and controls
43 lines (33 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.zetcode;
import com.opencsv.CSVWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class OpenCSVDatabaseEx {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb?serverTimezone=UTC&useSsl=false";
String user = "root";
String password = "andrea";
String fileName = "src/main/resources/cars.csv";
Path myPath = Paths.get(fileName);
try (var con = DriverManager.getConnection(url, user, password);
var pst = con.prepareStatement("SELECT * FROM cars");
var rs = pst.executeQuery()) {
try (var writer = new CSVWriter(Files.newBufferedWriter(myPath,
StandardCharsets.UTF_8), CSVWriter.DEFAULT_SEPARATOR,
CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER,
CSVWriter.DEFAULT_LINE_END)) {
writer.writeAll(rs, true);
}
} catch (SQLException | IOException ex) {
Logger.getLogger(OpenCSVDatabaseEx.class.getName()).log(
Level.SEVERE, ex.getMessage(), ex);
}
}
}