Using connections
When you need to execute sequential queries (without a transaction), you can create a new connection or borrow one from the pool:
pool.getConnection(ar1 -> {
if (ar1.succeeded()) {
SqlConnection connection = ar1.result();
connection.query("SELECT * FROM users WHERE id='julien'", ar2 -> {
if (ar1.succeeded()) {
connection.query("SELECT * FROM users WHERE id='paulo'", ar3 -> {
// Do something with rows and return the connection to the pool
connection.close();
});
} else {
// Return the connection to the pool
connection.close();
}
});
}
});
Prepared queries can be created:
connection.prepare("SELECT * FROM users WHERE first_name LIKE $1", ar1 -> {
if (ar1.succeeded()) {
PreparedQuery pq = ar1.result();
pq.execute(Tuple.of("julien"), ar2 -> {
if (ar2.succeeded()) {
// All rows
RowSet rows = ar2.result();
}
});
}
});
|
Note
|
prepared query caching depends on the setCachePreparedStatements and
does not depend on whether you are creating prepared queries or use direct prepared queries
|
PreparedQuery can perform efficient batching:
connection.prepare("INSERT INTO USERS (id, name) VALUES ($1, $2)", ar1 -> {
if (ar1.succeeded()) {
PreparedQuery prepared = ar1.result();
// Create a query : bind parameters
List<Tuple> batch = new ArrayList();
// Add commands to the createBatch
batch.add(Tuple.of("julien", "Julien Viet"));
batch.add(Tuple.of("emad", "Emad Alblueshi"));
prepared.batch(batch, res -> {
if (res.succeeded()) {
// Process rows
RowSet rows = res.result();
} else {
System.out.println("Batch failed " + res.cause());
}
});
}
});