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