gpt4 book ai didi

c++ - 如何使用 MySQL Connector C++ 与数据库建立连接?

转载 作者:行者123 更新时间:2023-11-29 20:16:17 27 4
gpt4 key购买 nike

我正在尝试在 C++ 项目中与 MySQL 数据库建立连接。
我按照 link 中给出的说明进行操作。 .
安装 Cmake 后,我在构建和安装 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 get_driver_instance',但它是在driver.h`中定义的。

最佳答案

终于,我找到了解决方案:)

首先,我从系统(MySQL Client、MYSQL Server 和 libmysqlcppconn-dev)中完全卸载了MySQL

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

  1. 安装 MySQL 客户端和服务器。
  2. sudo apt-get install libmysqlcppconn-dev

现在确保您已安装所有依赖项

  • sudo apt-get build-dep libmysqlcppconn-dev
  • 现在使用 -lmysqlcppconn 构建包。

    关于c++ - 如何使用 MySQL Connector C++ 与数据库建立连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39772488/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com