How can we store and retrieve JSON data to a database i…
To store JSON data in a database, you can utilize database connection libraries in C++, such as MySQL Connector/C++ or SQLite C/C++ Interface.
Here is an example code of storing JSON data in a MySQL database.
#include <iostream>
#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/exception.h>
#include <json/json.h>
using namespace std;
int main() {
try {
sql::mysql::MySQL_Driver *driver;
sql::Connection *con;
// 创建MySQL连接
driver = sql::mysql::get_mysql_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "username", "password");
// 选择数据库
con->setSchema("database_name");
// 准备JSON数据
Json::Value json;
json["name"] = "John";
json["age"] = 30;
json["city"] = "New York";
// 插入JSON数据
sql::PreparedStatement *stmt;
stmt = con->prepareStatement("INSERT INTO table_name (json_data) VALUES (?)");
stmt->setString(1, json.toStyledString());
stmt->execute();
delete stmt;
// 查询数据库中的JSON数据
sql::Statement *query;
sql::ResultSet *res;
query = con->createStatement();
res = query->executeQuery("SELECT * FROM table_name");
while (res->next()) {
Json::Value result;
Json::Reader reader;
reader.parse(res->getString("json_data"), result);
cout << "Name: " << result["name"].asString() << endl;
cout << "Age: " << result["age"].asInt() << endl;
cout << "City: " << result["city"].asString() << endl;
}
delete res;
delete query;
delete con;
} catch (sql::SQLException &e) {
cout << "MySQL Error: " << e.what() << endl;
}
return 0;
}
Please replace the username, password, database_name, and table_name in the code with your actual database information. This example code uses MySQL database and JSONcpp library to handle JSON data, you will also need to download and install the corresponding libraries.
The idea behind the above code is to convert JSON data into a string and store it in a database field, then convert it back into a JSON object during querying for parsing and processing. You can adjust and modify it according to actual needs.