0
我想在C++項目中建立與MySQL數據庫的連接。
而且我遵循link中的說明。
安裝Cmake後,我在Build &中遇到問題安裝MySQL Connector/C++。
因爲CmakeLists.txt
在目錄中不存在。
經過在網上搜索後,我發現this answer,並按照給定的步驟,但它不適用於我的情況。
如何使用MySQLConnectorC++建立與數據庫的連接?
沮喪將這一切,我把所有的文件(摘自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`。