Skip to content

在macOS Catalina上通过CLion使用MySQL Connector/C++ 8.0

安装MySQL Connector/C++

到官网下载:下载地址

根据自己的系统版本架构和MySQL的版本选择合适的安装包。

1

下载dmg文件安装,默认会安装到/usr/local/mysql-connector-c++-8.0.27

2

同时也会生成两个替身(快捷方式)。

使用CLion创建一个新的C++项目,并在CMakeLists.txt中加入如下三行内容:

cmake
include_directories(/usr/local/mysql/include) # 头文件目录
link_directories(/usr/local/mysql-connector-c++/lib64) # 链接库目录

target_link_libraries(cppMysqlTest -lmysqlcppconn-static -lssl -lcrypto) # 要链接的库文件

3

Reload CMake Project之后,需要将如下两个文件拷贝到二进制文件运行的目录下,也就是上图cmake-build-debug目录下:

  • /usr/local/mysql-connector-c++-8.0.27/libssl.1.1.dylib
  • /usr/local/mysql-connector-c++-8.0.27/libcrypto.1.1.dylib

可以使用替身,但是文件名不要错。

然后在main.cpp中编写代码,连接并操作MySQL。

c++
#include <mysql.h>
#include <iostream>

#define LOG(s) std::cout<<__FILE__<<" : "<<__LINE__<<" "<<__TIMESTAMP__<<" : "<<s<<std::endl;

class MySQL {
public:
    MySQL() {
        _conn = mysql_init(nullptr);
    }

    ~MySQL() {
        if (!_conn)
            mysql_close(_conn);
    }

    bool connect(const std::string &host, unsigned short port, const std::string &user,
                 const std::string &password, const std::string &dbname) {
        MYSQL *p = mysql_real_connect(_conn, host.c_str(), user.c_str(),
                                      password.c_str(), dbname.c_str(), port, nullptr, 0);//mysql.h中的连接,传入参数即可
        return p != nullptr;
    }

    bool update(const std::string &sql) {
        if (mysql_query(_conn, sql.c_str())) {
            LOG("update failed " + sql);
            return false;
        }
        return true;
    }

    MYSQL_RES *query(const std::string &sql) {
        if (mysql_query(_conn, sql.c_str())) {
            LOG("query failed " + sql);
            return nullptr;
        }
        return mysql_store_result(_conn);
    }

private:
    MYSQL *_conn; // represent a connection between Mysql and server
};

int main() {
    // 把下面配置信息修改为自己数据库的
    const std::string host = "127.0.0.1";
    const std::string user = "root";
    const std::string pwd = "123456";
    const std::string database = "test";
    unsigned short port = 3306;
    MySQL conn;
    conn.connect(host, port, user, pwd, database);
    conn.update("insert into user(name, age, sex) values('zhang san',20,'male')");
    MYSQL_RES *res = conn.query("SELECT * FROM user");
//    std::cout << mysql_num_rows(res) << std::endl;
    unsigned int num_fields = mysql_num_fields(res);
    MYSQL_ROW row ;
    row = mysql_fetch_row(res);
    while (row){
        for (int i = 0; i < num_fields; i++)
        {
            char *filed = row[i];
            std::cout << filed << " ";
        }
        std::cout << std::endl;
        row = mysql_fetch_row(res);
    }
    return 0;
}

直接运行就可以了!

4