MySql Connector/c++8中JSON处理Demo

#include <iostream>
#include <vector>
#include <mysqlx/xdevapi.h>

using std::cout;
using std::endl;

int main(void)
try
{
    mysqlx::Session sess("mysqlx://root:mysql@localhost:33060?ssl-mode=disabled");

    //参数true表示检测给定的"D_COMPANY"是否存在, 如果不存在则抛出异常
    //"D_COMPANY" 为使用 【CREATE DATABASE XXXX】 语法创建的数据库名
    mysqlx::Schema db = sess.getSchema("D_COMPANY", true);

    //"C_DOCUMENT" 为表名
    //true 表示返回与此字符串匹配的已存在的表,不存在则抛出异常
    cout << ">> create collection.." << endl;
    mysqlx::Collection coll = db.createCollection("C_DOCUMENT", true);

#ifdef INSERT_DOCUMENT
    cout << ">> add document.." << endl;
    mysqlx::Result ret;
    //注意: _id字段是必要的
    ret = coll.add(
            R"(
            {
                "_id": "test", 
                "name": "Awesome 4K",
                "resolutions":  [{
                                "width":    1280,
                                "height":   720
                            }, {
                                "width":    1920,
                                "height":   1080
                            }, {
                                "width":    3840,
                                "height":   2160
                            }]
            }
            )").execute();

    std::vector<std::string> idList = ret.getGeneratedIds();

    cout << ">> print ID..." << endl;
    for (std::string str : idList) {
        cout << str << endl;
    }
#endif

#ifdef DELETE_DOCUMENT
    cout << ">> drop document..." << endl;
    mysqlx::Result ret = coll.removeOne(std::string("test"));
    cout << ">> Affect items: " << ret.getAffectedItemsCount() << endl;
#endif

    //得到_id为“test”的json数据
    mysqlx::DbDoc doc = coll.getOne(std::string("test"));
    if (doc.isNull()) {
        cout << "the doc is null." << endl;
        return 0;
    } else {
        cout << R"(">> Get a document with an identifier of "test")" << endl;
    }

    cout << ">> print document..." << endl;
    doc.print(cout);
    cout << endl;

    if (doc.fieldType("name")
                == int(mysqlx::Value::STRING))
    {
        cout << "name: " << doc["name"].get<std::string>() << endl;
    }

    if (doc.fieldType("resolutions") 
                == int(mysqlx::Value::ARRAY))
    {
        mysqlx::DbDoc resDoc = doc["resolutions"].get<mysqlx::DbDoc>();
        
        if (resDoc.isNull()) {
            cout << "res doc is null." << endl;
            return -1;
        }

        cout << "-----------------------" << endl;
        resDoc.print(cout);
        cout << endl;
    }



    cout << endl << ">> Done!" << endl;
}
catch(mysqlx::Error &err)
{
    cout << "ERROR: " << err << endl;
    return -1;
}

转载于:https://www.cnblogs.com/Focus-Flying/p/9320047.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值