#include <iostream>
#include "boost/asio.hpp"
#include "boost/mysql/connection_pool.hpp"
int main() {
boost::asio::io_context ctx{};
boost::mysql::pool_params params{};
params.server_address.emplace_host_and_port("localhost");
params.username = "root";
params.password = "123456";
params.database = "anubis";
static auto conn_pool = std::make_shared<boost::mysql::connection_pool>(
boost::mysql::pool_executor_params::thread_safe(ctx.get_executor()), std::move(params));
if (!conn_pool->valid()) {
return 1;
}
conn_pool->async_run(boost::asio::detached);
conn_pool->async_get_connection([&](boost::mysql::error_code ec, boost::mysql::pooled_connection conn) {
if (ec) {
return;
}
// query result ok
boost::mysql::diagnostics _errorInfo{};
boost::mysql::results _results{};
conn->execute("SELECT COUNT(*) FROM `character`;", _results, ec, _errorInfo);
if (ec) {
return;
}
for (auto rows : _results.rows()) {
for (std::size_t i = 0; i < rows.size(); ++i) {
auto field = rows[i];
std::cout << "execute:" << field.as_int64() << std::endl;
}
}
// query not result
static boost::mysql::diagnostics _errorInfo2{};
static boost::mysql::results _results2{};
conn->async_execute("SELECT COUNT(*) FROM `character`;", _results2, _errorInfo2,
[&](boost::mysql::error_code ec) {
if (ec) {
return;
}
// this rows is 0
for (auto rows : _results2.rows()) {
for (std::size_t i = 0; i < rows.size(); ++i) {
auto field = rows[i];
std::cout << "async_execute:" << field.as_int64() << std::endl;
}
}
});
});
ctx.run();
return 0;
}

Destroying a
pooled_connectionis how you tell the pool that you’re done using the connection and it can be recycled.Yes, I understand. I used to think that boost:: mysql:: pooled_connection was managed internally.
If you’re going to use callbacks, I’d advise to create a session object on the heap, storing all intermediate state that must be kept alive until the operation completes. For instance:
I haven’t built the code, it may contain typos.
Your
connvariable is getting destroyed right after callingconn->execute, which makes the connection to be returned to the pool while you’re still using it, causing undefined behavior. This should work: