C是一種高級(jí)編程語(yǔ)言,通常用來(lái)編寫操作系統(tǒng)和與硬件交互的軟件。但是,在Web開發(fā)中,C可以作為一種工具來(lái)將SQL轉(zhuǎn)換為JSON數(shù)據(jù)。
#include <mysql.h> #include <stdio.h> #include <jansson.h> int main(int argc, char **argv) { MYSQL mysql; MYSQL_RES *result; MYSQL_ROW row; char *query; int i, num_fields; json_t *result_json; json_t *array; json_t *row_json; mysql_init(&mysql); mysql_options(&mysql, MYSQL_READ_DEFAULT_GROUP, "your_prog_name"); mysql_real_connect(&mysql, "localhost", "user", "password", "database", 0, NULL, 0); query = "SELECT * FROM table"; mysql_query(&mysql, query); result = mysql_store_result(&mysql); num_fields = mysql_num_fields(result); result_json = json_object(); array = json_array(); while ((row = mysql_fetch_row(result))) { row_json = json_object(); for (i = 0; i < num_fields; i++) { json_object_set_new(row_json, mysql_fetch_field_direct(result, i)->name, json_string(row[i])); } json_array_append(array, row_json); } json_object_set_new(result_json, "result", array); printf("%s\n", json_dumps(result_json, JSON_INDENT(4))); }
以上代碼將SQL轉(zhuǎn)換成了JSON數(shù)據(jù),實(shí)現(xiàn)了從數(shù)據(jù)庫(kù)中獲取數(shù)據(jù)并將其轉(zhuǎn)換為可跨平臺(tái)使用的JSON格式。在此過(guò)程中,C作為一種工具很好地發(fā)揮了作用。