C语言读取data.json文件并存入MySQL数据库小案例(推荐)
作者:etsuyou
本文介绍如何使用C语言结合cJSON库读取JSON文件,并将数据存储到MySQL数据库中,示例代码包括创建MySQL表的SQL语句和C语言代码,以及如何编译和运行程序,确保已安装必要的库以支持程序运行
本地有一个data.json文件
data.json
[
{
"id": 1,
"name": "Alice",
"age": 30
},
{
"id": 2,
"name": "Bob",
"age": 25
}
]
要将 data.json 文件中的数据存储到 MySQL 数据库中,首先需要创建一个相应的数据库表。然后,你可以使用 C 语言和 cJSON 库来读取 JSON 文件并将数据插入到数据库中。
1. 创建 MySQL 表
首先,在 MySQL 中创建一个表来存储数据。可以使用以下 SQL 语句:
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(100),
age INT
);

2. C 语言代码示例
以下是一个完整的 C 语言示例,使用 cJSON 库读取 data.json 文件并将数据插入到 MySQL 数据库中。
依赖项
确保你已经安装了以下库:
- MySQL C API
- cJSON
代码示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql/mysql.h>
#include "cJSON.h"
// MySQL 配置
#define DB_HOST "xxx.xxx.xxx.xxx"
#define DB_USER "root"
#define DB_PASSWORD "xxxxxx"
#define DB_NAME "xxxxx"
void insert_user(MYSQL *conn, int id, const char *name, int age) {
char query[256];
snprintf(query, sizeof(query), "INSERT INTO users (id, name, age) VALUES (%d, '%s', %d)", id, name, age);
if (mysql_query(conn, query)) {
fprintf(stderr, "INSERT failed: %s\n", mysql_error(conn));
}
}
int main() {
// MySQL 连接
MYSQL *conn;
conn = mysql_init(NULL);
if (conn == NULL) {
fprintf(stderr, "mysql_init() failed\n");
return EXIT_FAILURE;
}
if (mysql_real_connect(conn, DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, 0, NULL, 0) == NULL) {
fprintf(stderr, "mysql_real_connect() failed\n");
mysql_close(conn);
return EXIT_FAILURE;
}
// 读取 JSON 文件
FILE *file = fopen("data.json", "r");
if (!file) {
perror("Could not open file");
mysql_close(conn);
return EXIT_FAILURE;
}
fseek(file, 0, SEEK_END);
long length = ftell(file);
fseek(file, 0, SEEK_SET);
char *data = malloc(length);
fread(data, 1, length, file);
fclose(file);
// 解析 JSON
cJSON *json = cJSON_Parse(data);
if (json == NULL) {
fprintf(stderr, "cJSON_Parse failed\n");
free(data);
mysql_close(conn);
return EXIT_FAILURE;
}
// 遍历 JSON 数组并插入数据
cJSON *user;
cJSON_ArrayForEach(user, json) {
int id = cJSON_GetObjectItem(user, "id")->valueint;
const char *name = cJSON_GetObjectItem(user, "name")->valuestring;
int age = cJSON_GetObjectItem(user, "age")->valueint;
insert_user(conn, id, name, age);
}
// 清理
cJSON_Delete(json);
free(data);
mysql_close(conn);
return EXIT_SUCCESS;
}
3. 编译和运行
新建一个makefile文件:
# 定义变量 CC = gcc CFLAGS = -Wall -g LIBS = -lm -lmysqlclient # 添加 MySQL 客户端库 TARGET = json_to_mysql SRC = main.c cJSON.c OBJ = $(SRC:.c=.o) # 默认目标 all: $(TARGET) # 构建目标 $(TARGET): $(OBJ) $(CC) $(CFLAGS) -o $@ $^ $(LIBS) # 编译 .c 文件为 .o 文件 %.o: %.c $(CC) $(CFLAGS) -c $< -o $@ # 清理目标 clean: rm -f $(TARGET) $(OBJ) # 伪目标 .PHONY: all clean
输入make编译:

运行


到此这篇关于C语言读取data.json文件并存入MySQL数据库小案例的文章就介绍到这了,更多相关C语言读取data.json文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
