Ubuntu c++ 使用mysql++ 链接mysql 使用cmake 构建
首先要安装MySQL
sudo apt install -y mysql-server mysql-client libmysqlclient-dev cat /etc/mysql/debian.cnf # 获取密码
mysql -udebian-sys-maint -p # 输入上面现实的密码 use mysql; alter user "root"@"localhost" identified with mysql_native_password by "新密码"; # 设置root密码 flush privileges; update user set host='%' where user='root'; # 设置远程链接 flush privileges; exit # 退出mysql sudo gedit /etc/mysql/mysql.conf.d/mysqld.cnf # 打开配置文件修改配置 bind-address = 0.0.0.0 # 修改,可以远程链接 # 可选项 可以默认 [mysqld] # # * Basic Settings # max_allowed_packet = 1024M sql_mode =STRICT_TRANS_TABLES # 重启 service mysql restart
安装mysql++
wget https://tangentsoft.com/mysqlpp/releases/mysql++-3.2.5.tar.gz tar -zxvf ./mysql++-3.2.5.tar.gz cd mysql++-3.2.5 ./configure make make install
创建test数据库,和abc表,可以使用 navicat,网上有安装方式
创建c++项目,使用Clion 选择c++17
#include <iostream> #include <mysql++/mysql++.h> int main() { const char* db = nullptr, *server = nullptr, *user = nullptr, *password = ""; db = "test"; server = "localhost"; user = "root"; password = "7355608"; mysqlpp::Connection conn(false); if (conn.connect(db, server, user, password)){ std::cout << "Hello, MySQL!" << std::endl; std::cout << "connect db succeed. " <<std::endl; mysqlpp::Query query = conn.query("SELECT * FROM abc"); if (mysqlpp::StoreQueryResult res = query.store()) { std::cout.setf(std::ios::left); std::cout << std::setw(31) << "name" << std::setw(10) << "age" << std::endl; mysqlpp::StoreQueryResult::const_iterator it; for (it = res.begin(); it != res.end(); ++it) { mysqlpp::Row row = *it; std::cout << std::setw(31) << row[0] << std::setw(10) << row[1] << std::endl; } } } return 0; }
CMakeLists.txt 编写
cmake_minimum_required(VERSION 3.17) project(sboost) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_COMPILER "g++") include_directories(/usr/include/mysql) include_directories(/usr/local/include/mysql++) add_executable(sboost main.cpp) target_link_libraries(sboost mysqlpp)
完结!