1.install mysql in ubuntu;
2install mysqlconnector;
sudo apt install libmysqlclient-dev
3.complete code
#include <algorithm> #include <chrono> #include <cstdio> #include <cstdint> #include <cstdlib> #include <ctime> #include <fstream> #include <iomanip> #include <iostream> #include <random> #include <sstream> #include <thread> #include <vector> #include <mysql_connection.h> #include <mysql_driver.h> #include <mysql_error.h> // #include <cppconn/driver.h> // #include <cppconn/connection.h> // #include <cppconn/exception.h> // #include <cppconn/metadata.h> // #include <cppconn/parameter_metadata.h> #include <cppconn/prepared_statement.h> #include <cppconn/resultset.h> #include <cppconn/resultset_metadata.h> // #include <cppconn/sqlstring.h> std::string get_time_now() { std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now(); time_t raw_time = std::chrono::high_resolution_clock::to_time_t(now); struct tm tm_info = *localtime(&raw_time); std::stringstream ss; ss << std::put_time(&tm_info, "%Y%m%d%H%M%S"); return ss.str(); } void connect_mysql() { try { sql::Driver *driver; sql::Connection *conn; sql::Statement *stmt; sql::ResultSet *res; driver = sql::mysql::get_driver_instance(); conn = driver->connect("tcp://127.0.0.1:3306", "root", "password!"); conn->setSchema("mysql"); stmt = conn->createStatement(); res = stmt->executeQuery("select * from db;"); sql::ResultSetMetaData *rsmd = res->getMetaData(); int column_count = rsmd->getColumnCount(); std::cout << "Number of rows : " << res->rowsCount() << std::endl; std::cout << "Number of columns : " << column_count << std::endl; while (res->next()) { for (int i = 1; i < column_count; i++) { std::cout << res->getString(i) << ","; } std::cout << res->getString(column_count) << std::endl; } delete res; delete stmt; delete conn; } catch (sql::SQLException &e) { std::cout << "# ERR: SQLException in " << __FILE__ << "(" << __FUNCTION__ << ") on line " << __LINE__ << std::endl; std::cout << "# ERR: " << e.what() << " (MySQL error code: " << e.getErrorCode() << ", SQLState: " << e.getSQLState() << " )" << std::endl; } } int main(int args, char **argv) { connect_mysql(); std::cout << get_time_now() << ",finished in " << __FUNCTION__ << std::endl; }
Compile
g++-12 -std=c++2a -I. *.cpp -o h1 -lmysqlcppconn
Run
./h1;
标签:std,now,chrono,++,column,time,cpp,include,mysqlconnector From: https://www.cnblogs.com/Fred1987/p/17572231.html