#include #include #include using tdMysqlResUPtr = std::unique_ptr; bool mysql_intit(const char* host, const unsigned int port, const char* user, const char* password, MYSQL& mysql) { mysql_init(&mysql); mysql_options(&mysql, MYSQL_OPT_NONBLOCK, 0); enum mysql_protocol_type protocol = MYSQL_PROTOCOL_TCP; mysql_optionsv(&mysql, MYSQL_OPT_PROTOCOL, &protocol); // disable attempt to connect through unix socket when specified localhost bool reconnect = false; mysql_optionsv(&mysql, MYSQL_OPT_RECONNECT, &reconnect); mysql_ssl_set(&mysql, nullptr, nullptr, nullptr, nullptr, nullptr); unsigned int cipher_strength = 128; mysql_optionsv(&mysql, MARIADB_OPT_TLS_CIPHER_STRENGTH, (void*)&cipher_strength); mysql_optionsv(&mysql, MYSQL_SET_CHARSET_NAME, (void*)"utf8"); unsigned int timeout = 10; mysql_optionsv(&mysql, MYSQL_OPT_CONNECT_TIMEOUT, (void*)&timeout); // seconds my_bool enableClearTextPlugin = 0; mysql_optionsv(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, &enableClearTextPlugin); // by default, by security reasons clear text plugin is disabled mysql_optionsv(&mysql, MYSQL_OPT_LOCAL_INFILE, (void*)"1"); // enable LOAD DATA functionality mysql_optionsv(&mysql, MARIADB_OPT_FOUND_ROWS, 1); MYSQL* ret = mysql_real_connect(&mysql, host, user, password, nullptr, port, nullptr, 0); if (!ret) { int code = static_cast(mysql_errno(&mysql)); std::cerr << code << ": " << mysql_error(&mysql) << "\n"; return false; } return true; } void run_query(const char* host, const unsigned int port, const char* user, const char* password, const std::string query) { int err, status = 0; MYSQL mysql; MYSQL_ROW row; if (!mysql_intit(host, port, user, password, mysql)) { return; } status = mysql_real_query_start(&err, &mysql, query.c_str(), (unsigned long)query.length()); while (status) { status = mysql_real_query_cont(&err, &mysql, status); } if (err) { int code = static_cast(mysql_errno(&mysql)); std::cerr << code << ": " << mysql_error(&mysql) << "\n"; return; } MYSQL_RES* res = mysql_use_result(&mysql); if (!res) { int code = static_cast(mysql_errno(&mysql)); std::cerr << code << ": " << mysql_error(&mysql) << "\n"; return; } for (;;) { status = mysql_fetch_row_start(&row, res); while (status) { status = mysql_fetch_row_cont(&row, res, status); } if (!row) break; printf("%s: %s\n", row[0], row[1]); } if (mysql_errno(&mysql)) { int code = static_cast(mysql_errno(&mysql)); std::cerr << code << ": " << mysql_error(&mysql) << "\n"; return; } mysql_free_result(res); mysql_close(&mysql); } int main(int /*argc*/, char**/*argv*/) { run_query("127.0.0.1", 3306, "login", "password", "select 1"); return 0; }