-
Notifications
You must be signed in to change notification settings - Fork 205
Expand file tree
/
Copy pathDB2ClientExamples.java
More file actions
430 lines (367 loc) · 12.1 KB
/
DB2ClientExamples.java
File metadata and controls
430 lines (367 loc) · 12.1 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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
* Copyright (C) 2019,2020 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.net.ClientSSLOptions;
import io.vertx.core.net.JksOptions;
import io.vertx.db2client.DB2Builder;
import io.vertx.db2client.DB2ConnectOptions;
import io.vertx.db2client.DB2Connection;
import io.vertx.docgen.Source;
import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import io.vertx.sqlclient.SqlClient;
import io.vertx.sqlclient.SqlResult;
import io.vertx.sqlclient.Tuple;
@Source
public class DB2ClientExamples {
public void gettingStarted() {
// Connect options
DB2ConnectOptions connectOptions = new DB2ConnectOptions()
.setPort(50000)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret");
// Pool options
PoolOptions poolOptions = new PoolOptions()
.setMaxSize(5);
// Create the client pool
Pool client = DB2Builder.pool()
.with(poolOptions)
.connectingTo(connectOptions)
.build();
// A simple query
client
.query("SELECT * FROM users WHERE id='julien'")
.execute()
.onComplete(ar -> {
if (ar.succeeded()) {
RowSet<Row> result = ar.result();
System.out.println("Got " + result.size() + " rows ");
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
// Now close the pool
client.close();
});
}
public void configureFromDataObject(Vertx vertx) {
// Data object
DB2ConnectOptions connectOptions = new DB2ConnectOptions()
.setPort(50000)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret");
// Pool Options
PoolOptions poolOptions = new PoolOptions().setMaxSize(5);
// Create the pool from the data object
Pool pool = DB2Builder.pool()
.with(poolOptions)
.connectingTo(connectOptions)
.using(vertx)
.build();
pool.getConnection()
.onComplete(ar -> {
// Handling your connection
});
}
public void configureFromUri(Vertx vertx) {
// Connection URI
String connectionUri = "db2://dbuser:secretpassword@database.server.com:50000/mydb";
// Create the pool from the connection URI
Pool pool = DB2Builder.pool()
.connectingTo(connectionUri)
.using(vertx)
.build();
// Create the connection from the connection URI
DB2Connection.connect(vertx, connectionUri)
.onComplete(res -> {
// Handling your connection
});
}
public void connecting01(Vertx vertx) {
// Connect options
DB2ConnectOptions connectOptions = new DB2ConnectOptions()
.setPort(50000)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret");
// Pool options
PoolOptions poolOptions = new PoolOptions()
.setMaxSize(5);
// Create the pooled client
SqlClient client = DB2Builder.client()
.with(poolOptions)
.connectingTo(connectOptions)
.using(vertx)
.build();
}
public void connecting02(Vertx vertx) {
// Connect options
DB2ConnectOptions connectOptions = new DB2ConnectOptions()
.setPort(50000)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret");
// Pool options
PoolOptions poolOptions = new PoolOptions()
.setMaxSize(5);
// Create the pooled client
SqlClient client = DB2Builder.client()
.with(poolOptions)
.connectingTo(connectOptions)
.using(vertx)
.build();
}
public void connecting03(SqlClient client) {
// Close the pool and all the associated resources
client.close();
}
public void connecting04(Vertx vertx) {
// Connect options
DB2ConnectOptions connectOptions = new DB2ConnectOptions()
.setPort(50000)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret");
// Pool options
PoolOptions poolOptions = new PoolOptions()
.setMaxSize(5);
// Create the pooled client
Pool client = DB2Builder.pool()
.with(poolOptions)
.connectingTo(connectOptions)
.using(vertx)
.build();
// Get a connection from the pool
client.getConnection().compose(conn -> {
System.out.println("Got a connection from the pool");
// All operations execute on the same connection
return conn
.query("SELECT * FROM users WHERE id='julien'")
.execute()
.compose(res -> conn
.query("SELECT * FROM users WHERE id='emad'")
.execute())
.onComplete(ar -> {
// Release the connection to the pool
conn.close();
});
}).onComplete(ar -> {
if (ar.succeeded()) {
System.out.println("Done");
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
}
public void poolVersusPooledClient(Vertx vertx, String sql, DB2ConnectOptions connectOptions, PoolOptions poolOptions) {
// Pooled client
SqlClient client = DB2Builder.client()
.with(poolOptions)
.connectingTo(connectOptions)
.using(vertx)
.build();
// Pipelined
Future<RowSet<Row>> res1 = client.query(sql).execute();
// Connection pool
Pool pool = DB2Builder.pool()
.with(poolOptions)
.connectingTo(connectOptions)
.using(vertx)
.build();
// Not pipelined
Future<RowSet<Row>> res2 = pool.query(sql).execute();
}
public void reconnectAttempts(DB2ConnectOptions options) {
// The client will try to connect at most 3 times at a 1 second interval
options
.setReconnectAttempts(2)
.setReconnectInterval(1000);
}
public void connecting05(Vertx vertx) {
// Pool options
DB2ConnectOptions options = new DB2ConnectOptions()
.setPort(50000)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret");
// Connect to DB2
DB2Connection.connect(vertx, options)
.compose(conn -> {
System.out.println("Connected");
// All operations execute on the same connection
return conn
.query("SELECT * FROM users WHERE id='julien'")
.execute()
.compose(res -> conn
.query("SELECT * FROM users WHERE id='emad'")
.execute()
).onComplete(ar -> {
// Close the connection
conn.close();
});
}).onComplete(res -> {
if (res.succeeded()) {
System.out.println("Done");
} else {
System.out.println("Could not connect: " + res.cause().getMessage());
}
});
}
public void connectSsl(Vertx vertx) {
DB2ConnectOptions options = new DB2ConnectOptions()
.setPort(50001)
.setHost("the-host")
.setDatabase("the-db")
.setUser("user")
.setPassword("secret")
.setSsl(true)
.setSslOptions(new ClientSSLOptions().setTrustOptions(new JksOptions()
.setPath("/path/to/keystore.p12")
.setPassword("keystoreSecret")));
DB2Connection.connect(vertx, options)
.onComplete(res -> {
if (res.succeeded()) {
// Connected with SSL
} else {
System.out.println("Could not connect " + res.cause());
}
});
}
public void generatedKeys(SqlClient client) {
client
.preparedQuery("SELECT color_id FROM FINAL TABLE ( INSERT INTO color (color_name) VALUES (?), (?), (?) )")
.execute(Tuple.of("white", "red", "blue"))
.onComplete(ar -> {
if (ar.succeeded()) {
RowSet<Row> rows = ar.result();
System.out.println("Inserted " + rows.rowCount() + " new rows.");
for (Row row : rows) {
System.out.println("generated key: " + row.getInteger("color_id"));
}
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
public void typeMapping01(Pool pool) {
pool
.query("SELECT an_int_column FROM exampleTable")
.execute().onSuccess(rowSet -> {
Row row = rowSet.iterator().next();
// Stored as INTEGER column type and represented as java.lang.Integer
Object value = row.getValue(0);
// Convert to java.lang.Long
Long longValue = row.getLong(0);
});
}
public void collector01Example(SqlClient client) {
// Create a collector projecting a row set to a map
Collector<Row, ?, Map<Long, String>> collector = Collectors.toMap(
row -> row.getLong("id"),
row -> row.getString("last_name"));
// Run the query with the collector
client.query("SELECT * FROM users")
.collecting(collector)
.execute()
.onComplete(ar -> {
if (ar.succeeded()) {
SqlResult<Map<Long, String>> result = ar.result();
// Get the map created by the collector
Map<Long, String> map = result.value();
System.out.println("Got " + map);
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
public void collector02Example(SqlClient client) {
// Create a collector projecting a row set to a (last_name_1,last_name_2,...)
Collector<Row, ?, String> collector = Collectors.mapping(
row -> row.getString("last_name"),
Collectors.joining(",", "(", ")")
);
// Run the query with the collector
client
.query("SELECT * FROM users")
.collecting(collector)
.execute()
.onComplete(ar -> {
if (ar.succeeded()) {
SqlResult<String> result = ar.result();
// Get the string created by the collector
String list = result.value();
System.out.println("Got " + list);
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
// Enum for days of the week
enum Days {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
/**
* Using an enum as a string value in the Row and Tuple methods.
*/
public void enumStringValues(SqlClient client) {
client.preparedQuery("SELECT day_name FROM FINAL TABLE ( INSERT INTO days (day_name) VALUES (?), (?), (?) )")
.execute(Tuple.of(Days.FRIDAY, Days.SATURDAY, Days.SUNDAY))
.onComplete(ar -> {
if (ar.succeeded()) {
RowSet<Row> rows = ar.result();
System.out.println("Inserted " + rows.rowCount() + " new rows");
for (Row row : rows) {
System.out.println("Day: " + row.get(Days.class, "day_name"));
}
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
/**
* Using an enum as an int value in the Row and Tuple methods.
* The row.get() method returns the corresponding enum's name() value at the ordinal position of the integer value retrieved.
*/
public void enumIntValues(SqlClient client) {
client.preparedQuery("SELECT day_num FROM FINAL TABLE ( INSERT INTO days (day_num) VALUES (?), (?), (?) )")
.execute(Tuple.of(Days.FRIDAY.ordinal(), Days.SATURDAY.ordinal(), Days.SUNDAY.ordinal()))
.onComplete(ar -> {
if (ar.succeeded()) {
RowSet<Row> rows = ar.result();
System.out.println("Inserted " + rows.rowCount() + " new rows");
for (Row row : rows) {
System.out.println("Day: " + row.get(Days.class, "day_num"));
}
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
}