-
Notifications
You must be signed in to change notification settings - Fork 51
/
H2Example.java
80 lines (66 loc) · 2.72 KB
/
H2Example.java
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package org.graalvm.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class H2Example {
public static final String JDBC_CONNECTION_URL = "jdbc:h2:./data/test";
public static void test() throws Exception {
// Cleanup
withConnection(JDBC_CONNECTION_URL, connection -> {
connection.prepareStatement("DROP TABLE IF EXISTS customers").execute();
connection.commit();
});
Set<String> customers = Set.of("Lord Archimonde", "Arthur", "Gilbert", "Grug");
System.out.println("=== Inserting the following customers in the database: ");
printCustomers(customers);
// Insert data
withConnection(JDBC_CONNECTION_URL, connection -> {
connection.prepareStatement("CREATE TABLE customers(id INTEGER AUTO_INCREMENT, name VARCHAR)").execute();
PreparedStatement statement = connection.prepareStatement("INSERT INTO customers(name) VALUES (?)");
for (String customer : customers) {
statement.setString(1, customer);
statement.executeUpdate();
}
connection.commit();
});
System.out.println("");
System.out.println("=== Reading customers from the database.");
System.out.println("");
Set<String> savedCustomers = new HashSet<>();
// Read data
withConnection(JDBC_CONNECTION_URL, connection -> {
try (ResultSet resultSet = connection.prepareStatement("SELECT * FROM customers").executeQuery()) {
while (resultSet.next()) {
savedCustomers.add(resultSet.getObject(2, String.class));
}
}
});
System.out.println("=== Customers in the database: ");
printCustomers(savedCustomers);
}
private static void printCustomers(Set<String> customers) {
List<String> customerList = new ArrayList<>(customers);
customerList.sort(Comparator.naturalOrder());
int i = 0;
for (String customer : customerList) {
System.out.println((i + 1) + ". " + customer);
i++;
}
}
private static void withConnection(String url, ConnectionCallback callback) throws SQLException {
try (Connection connection = DriverManager.getConnection(url)) {
connection.setAutoCommit(false);
callback.run(connection);
}
}
private interface ConnectionCallback {
void run(Connection connection) throws SQLException;
}
}