forked from vert-x3/vertx-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql_client_example.groovy
58 lines (50 loc) · 1.46 KB
/
sql_client_example.groovy
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
import io.vertx.pgclient.PgPool
import io.vertx.sqlclient.Tuple
def pool = PgPool.pool(vertx, [
port:5432,
host:"the-host",
database:"the-db",
user:"user",
password:"secret"
], [
maxSize:4
])
// Uncomment for MySQL
// Pool pool = MySQLPool.pool(vertx, new MySQLConnectOptions()
// .setPort(5432)
// .setHost("the-host")
// .setDatabase("the-db")
// .setUser("user")
// .setPassword("secret"), new PoolOptions().setMaxSize(4));
pool.getConnection({ res1 ->
if (res1.failed()) {
System.err.println(res1.cause().getMessage())
return
}
def connection = res1.result()
// create a test table
connection.query("create table test(id int primary key, name varchar(255))").execute({ res2 ->
if (res2.failed()) {
connection.close()
System.err.println("Cannot create the table")
res2.cause().printStackTrace()
return
}
// insert some test data
connection.query("insert into test values (1, 'Hello'), (2, 'World')").execute({ res3 ->
// query some data with arguments
connection.preparedQuery("select * from test where id = ?").execute(Tuple.of(2), { rs ->
if (rs.failed()) {
System.err.println("Cannot retrieve the data from the database")
rs.cause().printStackTrace()
return
}
rs.result().each { line ->
println("${line}")
}
// and close the connection
connection.close()
})
})
})
})