CPP Driver Part 2: Prepared Statements

CPP Driver Part 2: Prepared Statements

In the previous lesson, we introduced the C++ driver and saw how use it to connect to a ScyllaDB cluster and perform some basic operations. 

To improve performance, it’s almost always recommended to use Prepared Statements

This lesson will show us how to do this with the C++ driver. Prepared Statements are routinely employed to improve the speed of query execution. In short, they are a kind of parameterized CQL query that is “compiled” and cached by ScyllaDB. When reused, they save ScyllaDB from parsing CQL on every request.

We will start by reviewing concepts and the code; after that, you will run the lab yourself. 

The C/C++ driver supports them with the following syntax. 

Because it’s easy to make a mistake in the position of a particular argument in a row, the C/C++ driver supports a feature called “binding by column name”. This is an example of how it would be used:

To test this, you would replace the line:

In the file prepared_statements.cpp, with the above line. It’s that simple to bind by column name. 

Similarly, parameters can also be given explicit names, indicated by a colon:

If you read the above example carefully, you might have observed another benefit of prepared statements: no need to put string literals in single quotes (no need to escape literals). That’s because the driver sends the parameterized query separately from the parameters themselves. We can do a similar trick with simple statements- parameterize them – either by question marks or by names. 

Careful, though, not to confuse parameterized simple statements with prepared statements. Prepared Statements are “compiled” on a node once and from then onwards are referenced from the client app using a unique ID. On the other hand, simple statements are sent in text form every time they are executed. The only thing they have in common is that they send their parameters separately and thus don’t need escaping.

Summary 

In this lesson, we saw an example of how to use prepared statements with the CPP driver. Using prepared statements improves performance, as the statement’s preprocessing is done only once. Another advantage is that prepared statements also provide better security—they protect against SQL (CQL) injection. We also saw simple statements and an example of how to use them. 

fa-angle-up