本文主要介绍使用C++语言连接和操作 MySQL 数据库的方法。

1. 准备

本文利用 MySQL++ 接口进行C++语言的数据库编程。

MySQL++ 的官网定义如下:

MySQL++ is a C++ wrapper for MySQL’s C API. It is built around the same
principles as the Standard C++ Library, to make dealing with the database as
easy as dealing with STL containers. In addition, MySQL++ provides facilities
that let you avoid the most repetitive sorts of SQL within your own code,
providing native C++ interfaces for these common tasks.

为了使用 MySQL++ 接口编写C++程序,首先需要安装 MySQL++ ,本文使用 yum 命令安装 MySQL++ ,如下:
yum install mysql++-devel.x86_64 mysql++.x86_64 -y
同时,MySQL++ 需要用到 MySQL devel 的文件,所以也需要安装 mysql-devel,如下:
yum install mysql-community-devel.x86_64 -y
说明:关于 MySQL(mysql-community-*) 相关文件的安装,请点击此处
<https://blog.csdn.net/liitdar/article/details/80410910>。



2. 编写C++程序

我们本次编写一个简单的连接、操作数据库的C++程序,代码(mysql_test.cpp)如下:
#include <iostream> #include "mysql++.h" using namespace std; int main() {
const char* db = "testdb"; const char* server = "192.168.213.130"; const char*
user = "root"; const char* password = ""; // 创建数据库连接 mysqlpp::Connection
conn(false); // 连接数据库 if (conn.connect(db, server, user, password)) { cout <<
"connect db succeed." << endl; // 查询操作,查询结果保存在 query 中 mysqlpp::Query query =
conn.query("SELECT * FROM roles"); // 处理并打印查询结果 if (mysqlpp::StoreQueryResult
res = query.store()) { // 输出数据左对齐 cout.setf(ios::left); // 字段宽度为20位 // 打印表的字段名
cout << setw(21) << "role_id" << setw(21) << "occupation" << setw(21) << "camp"
<< endl; // 打印查询结果 mysqlpp::StoreQueryResult::const_iterator it; for (it =
res.begin(); it != res.end(); ++it) { mysqlpp::Row row = *it; cout << setw(20)
<< row[0] << ' ' << setw(20) << row[1] << ' ' << setw(20) << row[2] << ' ' <<
endl; } } } else { cout << "connect db fail." << endl; } return 0; }
编译生成可执行程序,如下:
g++ -o mysql_test mysql_test.cpp -I/usr/include/mysql++/ -I/usr/include/mysql/
-lmysqlpp
3. 测试

本次编写的代码连接的数据库位于 192.168.213.130 服务器上,相关的数据库信息参考源代码内容。

运行上面编译生成的程序,如下:




上述结果表明,我们编写的程序 mysql_test 成功地执行了连接、查询数据库操作。



友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信