C語言是一種經(jīng)典的編程語言,在處理大數(shù)據(jù)時表現(xiàn)出色。而Json是一種輕量級數(shù)據(jù)交換格式,被廣泛應用于前后端數(shù)據(jù)傳遞。如何在C語言中從數(shù)據(jù)庫讀取Json數(shù)據(jù)呢?
#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
#include <json-c/json.h>
#define HOST "localhost"
#define USER "root"
#define PASS "password"
#define DB "mydb"
int main()
{
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *query;
int state;
conn = mysql_init(NULL);
if(!mysql_real_connect(conn, HOST, USER, PASS, DB, 0, NULL, 0))
{
printf("Failed to connect to database: Error:%s\n", mysql_error(conn));
exit(1);
}
query = "SELECT * FROM mytable WHERE id=1";
state = mysql_query(conn, query);
if(state != 0)
{
printf("Failed to execute query: %s\n", mysql_error(conn));
exit(1);
}
res = mysql_store_result(conn);
if(res == NULL)
{
printf("Failed to get result set: %s\n", mysql_error(conn));
exit(1);
}
row = mysql_fetch_row(res);
if(row == NULL)
{
printf("No data returned!\n");
exit(1);
}
char *json_str = row[1];
json_object *json = json_tokener_parse(json_str);
printf("Id: %s\nName: %s\nAge: %d\n", row[0], json_object_get_string(json_object_object_get(json, "name")),
json_object_get_int(json_object_object_get(json, "age")));
mysql_free_result(res);
mysql_close(conn);
return 0;
}
以上就是使用C語言從數(shù)據(jù)庫讀取Json的方法,核心部分在于使用json-c庫解析得到Json對象,然后用其提供的接口讀取Json數(shù)據(jù)。需要注意的是,應根據(jù)自己的情況修改宏定義。