JSON是一種輕量級的數據交換格式,其語法與其他編程語言易于解析和生成。
C語言作為一種廣泛應用的編程語言,也可以通過JSON格式來導入數據庫并進行操作。
示例JSON數據: { "name": "Tom", "age": 18, "score": { "math": 90, "english": 80, "science": 95 } } 示例C代碼: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <mysql/mysql.h> #include <json-c/json.h> int main(int argc, char **argv) { MYSQL mysql; mysql_init(&mysql); if (!mysql_real_connect(&mysql, "localhost", "root", "123456", "test", 0, NULL, 0)) { printf("Connect failed: %s\n", mysql_error(&mysql)); exit(1); } char *json_str = "{\"name\":\"Tom\",\"age\":18,\"score\":{\"math\":90,\"english\":80,\"science\":95}}"; struct json_object *json = json_tokener_parse(json_str); struct json_object *name, *age, *score, *math, *english, *science; json_object_object_get_ex(json, "name", &name); json_object_object_get_ex(json, "age", &age); json_object_object_get_ex(json, "score", &score); json_object_object_get_ex(score, "math", &math); json_object_object_get_ex(score, "english", &english); json_object_object_get_ex(score, "science", &science); char sql[1024]; sprintf(sql, "INSERT INTO student (name, age, math, english, science) VALUES ('%s', %d, %d, %d, %d)", json_object_get_string(name), json_object_get_int(age), json_object_get_int(math), json_object_get_int(english), json_object_get_int(science)); mysql_query(&mysql, sql); mysql_close(&mysql); return 0; }
上述示例代碼通過JSON格式導入學生信息到MySQL數據庫中,通過使用json-c庫解析JSON數據,再通過MySQL C API進行數據庫操作。
C語言與JSON格式的結合,可以方便地進行數據導入和操作,也提高了數據的可讀性和可維護性。