本文主要介绍基于 C++ 编程语言,实现 MySQL 数据库编程的相关知识。

1 概述

本文利用 MySQL++ 接口实现基于 C++ 编程语言的 MySQL 数据库编程。

官网中对于 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.

2 安装MySQL++

为了使用 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-*) 相关文件的详细安装方法,请参考此文。

3 示例程序

在此编写一个简单的连接、操作 MySQL 数据库的 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

4 运行测试

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

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

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

更多推荐

MySQL数据库编程(C++)介绍