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

本文主要介绍基于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数据库操作。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liitdar

赠人玫瑰,手有余香,君与吾共勉

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值