The following small code examples illustrate how to use CppCrate. Feel free to contact the documentation of the used classes to get more information.
- Warning
- For real code do not forget to add proper error handling. You have been warned 😉
Connection
Simple connection
if (client.
connect(
"http://localhost:4200")) { ... }
or
client.
connect(
"http://localhost:4200");
Connect to a cluster and use all cluster nodes as fall-back
if (client.
connect(preferredNode)) {
if (!nodes.empty()) {
auto it = std::find(nodes.begin(), nodes.end(), preferredNode);
if (it != nodes.end()) {
std::iter_swap(nodes.begin(), it);
}
}
}
}
SQL Interface
Just give me JSON!
if (result) {
std::cout << result.
reply() <<
"\n";
}
Let CppCrate do the JSON parsing
std::cout << record.
value(
"port").asInt() <<
"\n";
}
Wait, give me JSON and then, maybe, parse it...
Browse through a result set
if (result) {
for (
int i = 0, total = result.
recordSize(); i < total; ++i) {
}
}
Don't be verbose, use a default schema
Prepare queries and reuse them (parameter substitution)
query.setArguments("[\"Calvin\"]");
query.setArguments("[\"Hobbes\"]");
Bulk operation
std::vector<std::string> bulk;
bulk.emplace_back("[\"Calvin\"]");
bulk.emplace_back("[\"Hobbes\"]");
query.setBulkArguments(bulk);
}
I'm in a hurry: change and get the results back immediately
client.
execRaw(
"UPDATE players SET age = 42");
client.
execRaw(
"SELECT * FROM players");
Blob Interface
Create a new blob table
Create a new blob table and store it at /fs/myblob
Upload an image
std::ifstream image;
image.open("/path/to/image", std::ifstream::in | std::ifstream::binary);
if (image) {
if (result) {
}
}
Check if an image exists
if (client.
existsBlob(
"myblob",
"93390aa9ed64e1e96149ceb0262f34aa2aedcffc")) {
}
Now, get me the image back
std::ofstream image;
image.open("/path/where/to/download/the/image", std::ifstream::out | std::ifstream::binary);
if (image) {
client.
downloadBlob(
"myblob",
"93390aa9ed64e1e96149ceb0262f34aa2aedcffc", image);
}
The image is mine, delete it
client.
deleteBlob(
"myblob",
"93390aa9ed64e1e96149ceb0262f34aa2aedcffc");
I have enough, delete the entire blob table