如何使用 C++ (ubuntu) 连接到 MySQL 数据库
Posted
技术标签:
【中文标题】如何使用 C++ (ubuntu) 连接到 MySQL 数据库【英文标题】:How to connect to MySQL database with C++ (ubuntu) 【发布时间】:2017-09-07 05:32:14 【问题描述】:我不确定如何在 Ubuntu Linux 上使用 C++ 连接到 mysql 数据库。 具体来说,我希望能够创建一个名为“new”的数据库。我不确定在哪里放置查询。下面是我正在使用的代码。
driver = get_driver_instance(); 给我错误消息undefined reference to 'get_driver_instance'
#include <cstdlib>
#include "mysql_driver.h"
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(int argc, char** argv)
cout << endl;
cout << "Running 'SELECT 'Hello World!' AS _message'..." << endl;
try
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
/* Write your own driver details */
con = driver->connect("tcp://127.0.0.1:3306", "root", "pass");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
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 data 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 ";
cout << __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
cout << endl;
return EXIT_SUCCESS;
【问题讨论】:
How to connect mySQL database using C++的可能重复 您的确切问题已在this answer 中解决。 【参考方案1】:在你的终端上试试这个命令:
~# sudo g++ -Wall -I/usr/include/cppconn -o <output name> <codename.cpp> -L/usr/lib -lmysqlcppconn
【讨论】:
以上是关于如何使用 C++ (ubuntu) 连接到 MySQL 数据库的主要内容,如果未能解决你的问题,请参考以下文章
使用 websocketpp 库连接到 c++ websocket 服务器
如何使用 Windows 将我的 Django 项目连接到 MySql?
如何从 ubuntu box 连接到 AWS Client ***?
如何不从 C++ 连接到 gRPC C++ InProcessChannel?
OPENCV 2.4.9 使用 basler pylon4 连接到 basler gige 相机和 ubuntu14.04