A robust, modern C++17 wrapper for the MySQL Connector/C++ library. It simplifies database interactions by providing type-safe parameter binding, automatic connection management, and RAII-based transaction support.
- Modern C++17: Utilizes Fold Expressions for elegant variadic templates and
std::string_view. - Google Style: Code follows the Google C++ Style Guide.
- Thread Safety: Basic thread safety for connection sharing (though individual instances per thread are recommended).
- RAII Transactions: Automatic rollback on scope exit prevents data inconsistency and deadlocks.
- Pluggable Logging: Integrate with any logging library (glog, spdlog, or simple stdout) via callbacks.
- Auto-Reconnect: Automatically attempts to restore lost connections before executing commands.
- C++17 compliant compiler (GCC 7+, Clang 5+, MSVC 2017+)
- MySQL Connector/C++ (libmysqlcppconn)
- Ensure
libmysqlcppconn-devis installed. - Include
easy_mysql.hand compileeasy_mysql.ccwith your project. - Link against the MySQL connector library (
-lmysqlcppconn).
#include "easy_mysql.h"
#include <iostream>
int main() {
easymysql::EasyMySQL db;
// Optional: Inject a custom logger
db.SetLogger([](easymysql::LogLevel level, const std::string& msg) {
if (level == easymysql::LogLevel::kError) {
std::cerr << "[DB-ERR] " << msg << std::endl;
} else {
std::cout << "[DB-LOG] " << msg << std::endl;
}
});
easymysql::DbConfig config;
config.host = "localhost";
config.user = "root";
config.password = "secret";
config.database = "test_db";
if (!db.Connect(config)) {
return -1;
}