如何使用MySQLConnectorC ++建立与数据库的连接?

时间:2016-09-29 14:01:49

标签: c++ mysql boost c++14

我正在尝试在C ++项目中建立与MySQL数据库的连接。
我按照link中的说明进行操作。
安装Cmake之后,我在Build& amp;安装MySQL Connector / C ++。由于目录中不存在CmakeLists.txt
在网上进行一些搜索后,我找到了this answer并按照给出的步骤进行了操作,但它没有在我的情况下工作。

这一切都令人沮丧,我将所有文件(从dowload link of MySQLConnector C++中提取)复制到我的项目文件夹中,并尝试使用这段代码建立连接。

/* Standard C++ includes */

#include <cstdlib>
#include <iostream>

/*
  Include directly the different headers from cppconn/ and mysql_driver.h + mysql_util.h
  (and mysql_connection.h). This will reduce your build time!
*/

#include "mysql_connection.h"
#include "mysql_driver.h"
#include "cppconn/driver.h"
#include "cppconn/exception.h"
#include "cppconn/resultset.h"
#include "cppconn/statement.h"

using namespace std;
using namespace sql::mysql;

void db_connection() {
    try {
        sql::Driver *driver;
        sql::Connection *con;
        sql::Statement *stmt;
        sql::ResultSet *res;
        /* Create a connection */
        driver = get_driver_instance();
        con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
        /* Connect to the MySQL test database */
        con->setSchema("test");

        stmt = con->createStatement();
        res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
        while (res->next()) {
            cout << "\t... MySQL replies: ";
            /* Access column data by alias or column name */
            cout << res->getString("_message") << endl;
            cout << "\t... MySQL says it again: ";
            /* Access column fata by numeric offset, 1 is the first column */
            cout << res->getString(1) << endl;
        }
        delete res;
        delete stmt;
        delete con;

    } catch (sql::SQLException &e) {
        cout << "# ERR: SQLException in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
        cout << "# ERR: " << e.what();
        cout << " (MySQL error code: " << e.getErrorCode();
        cout << ", SQLState: " << e.getSQLState() << " )" << endl;
    }

    cout << endl;
}

但它说,undefined reference to get_driver_instance', but it is defined in driver.h`。

1 个答案:

答案 0 :(得分:0)

最后,我找到了解决方案:)

首先,我完全从系统MySQL

卸载了(MySQL Client, MYSQL Server and libmysqlcppconn-dev).

之后,再次安装所有这些。

  1. 安装MySQL客户端和服务器。
  2. sudo apt-get install libmysqlcppconn-dev
  3. 现在确保已安装所有依赖项

    1. sudo apt-get build-dep libmysqlcppconn-dev
    2. 现在使用-lmysqlcppconn构建程序包。