forked from vert-x3/vertx-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JDBCExample.java
103 lines (87 loc) · 2.83 KB
/
JDBCExample.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package io.vertx.example.jdbc.transaction;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.example.util.Runner;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.sql.SQLConnection;
/*
* @author <a href="mailto:[email protected]">Paulo Lopes</a>
*/
public class JDBCExample extends AbstractVerticle {
// Convenience method so you can run it in your IDE
public static void main(String[] args) {
Runner.runExample(JDBCExample.class);
}
@Override
public void start() throws Exception {
final JDBCClient client = JDBCClient.createShared(vertx, new JsonObject()
.put("url", "jdbc:hsqldb:mem:test?shutdown=true")
.put("driver_class", "org.hsqldb.jdbcDriver")
.put("max_pool_size", 30));
client.getConnection(conn -> {
if (conn.failed()) {
System.err.println(conn.cause().getMessage());
return;
}
// create a test table
execute(conn.result(), "create table test(id int primary key, name varchar(255))", create -> {
// start a transaction
startTx(conn.result(), beginTrans -> {
// insert some test data
execute(conn.result(), "insert into test values(1, 'Hello')", insert -> {
// commit data
endTx(conn.result(), commitTrans -> {
// query some data
query(conn.result(), "select count(*) from test", rs -> {
for (JsonArray line : rs.getResults()) {
System.out.println(line.encode());
}
// and close the connection
conn.result().close(done -> {
if (done.failed()) {
throw new RuntimeException(done.cause());
}
});
});
});
});
});
});
});
}
private void execute(SQLConnection conn, String sql, Handler<Void> done) {
conn.execute(sql, res -> {
if (res.failed()) {
throw new RuntimeException(res.cause());
}
done.handle(null);
});
}
private void query(SQLConnection conn, String sql, Handler<ResultSet> done) {
conn.query(sql, res -> {
if (res.failed()) {
throw new RuntimeException(res.cause());
}
done.handle(res.result());
});
}
private void startTx(SQLConnection conn, Handler<ResultSet> done) {
conn.setAutoCommit(false, res -> {
if (res.failed()) {
throw new RuntimeException(res.cause());
}
done.handle(null);
});
}
private void endTx(SQLConnection conn, Handler<ResultSet> done) {
conn.commit(res -> {
if (res.failed()) {
throw new RuntimeException(res.cause());
}
done.handle(null);
});
}
}