环境:
Windows11-24H2
CodeBlocks-25.03
gcc-14.20
wxwidgets-3.3.1
boost-1.89
openssl-3.5.2
CldeBlock配置:
在工程上点右键--build options...
界面:
代码:
头文件
#include <boost/mysql.hpp>
#include <boost/mysql/any_address.hpp>
#include <boost/mysql/any_connection.hpp>
#include <boost/mysql/connect_params.hpp>
#include <boost/mysql/error_with_diagnostics.hpp>
#include <boost/mysql/pfr.hpp>
#include <boost/mysql/static_results.hpp>
#include <boost/mysql/with_params.hpp>
#include <boost/mysql/results.hpp>
#include <boost/mysql/row_view.hpp>
#include <boost/asio/awaitable.hpp>
#include <boost/asio/co_spawn.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/this_coro.hpp>
#include <boost/charconv.hpp>
void wxsqlFrame::OnButton1Click(wxCommandEvent& event)
{
wxString str_hostname;
wxString str_port;
wxString str_username;
wxString str_password;
wxString str_database;
str_hostname = m_hostname->GetValue();
str_port = m_port->GetValue();
str_username = m_username->GetValue();
str_password = m_password->GetValue();
str_database = m_database->GetValue();
// The execution context, required to run I/O operations.
boost::asio::io_context ctx;
// Represents a connection to the MySQL server.
boost::mysql::any_connection conn(ctx);
// The hostname, username and password to use
boost::mysql::connect_params params;
params.server_address.emplace_host_and_port(std::string(str_hostname.mb_str()), wxAtoi(str_port));
params.username = str_username;
params.password = str_password;
params.database = str_database;
try
{
// Connect to the server
conn.connect(params);
// Execute the query with the given parameters. When executed, with_params
// expands the given query string template and sends it to the server for execution.
// {} are placeholders, as in std::format. Values are escaped as required to prevent
// SQL injection.
const char* sql = "SELECT username, nickname FROM wx_admin WHERE id = 2";
boost::mysql::results result;
conn.execute(sql, result);
// Did we find an employee with that ID?
if (result.rows().empty())
{
wxMessageBox(L"没有找到!");
}
else
{
// Print the retrieved details. The first field is the first name,
// and the second, the last name.
wxString msg;
std::string u_name = result.rows().at(0).at(0).as_string();
std::string n_name = result.rows().at(0).at(1).as_string();
msg << L"用户名是: " << u_name << L"\n昵称是: " << n_name;
wxMessageBox(msg, L"数据库内容");
}
// Close the connection
conn.close();
}
catch (const boost::mysql::error_with_diagnostics& err)
{
// Some errors include additional diagnostics, like server-provided error messages.
// Security note: diagnostics::server_message may contain user-supplied values (e.g. the
// field value that caused the error) and is encoded using to the connection's character set
// (UTF-8 by default). Treat is as untrusted input.
wxMessageBox(err.what());
}
}