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;
}


posted @ 2018-07-16 20:49  gluo-dreamer  阅读(630)  评论(0编辑  收藏  举报