c語言可以通過各種庫來操作數(shù)據(jù)庫,從而實現(xiàn)對數(shù)據(jù)庫中數(shù)據(jù)的增刪改查等操作。在進行數(shù)據(jù)交互時,一般需要將數(shù)據(jù)庫中的數(shù)據(jù)轉(zhuǎn)換成json格式,以方便傳輸和處理。下面將通過代碼演示c語言如何將數(shù)據(jù)庫中的數(shù)據(jù)轉(zhuǎn)換成json格式。
#include#include #include #include #include // 定義mysql連接信息 const char* HOST = "localhost"; const char* USER = "root"; const char* PASSWORD = "123456"; const char* DATABASE = "test"; int main() { // 初始化mysql連接 MYSQL mysql; mysql_init(&mysql); // 連接mysql數(shù)據(jù)庫 if (!mysql_real_connect(&mysql, HOST, USER, PASSWORD, DATABASE, 0, NULL, 0)) { printf("Failed to connect to database: Error: %s\n", mysql_error(&mysql)); return 1; } // 查詢數(shù)據(jù)庫中的數(shù)據(jù) if (mysql_query(&mysql, "SELECT * FROM userinfo")) { printf("Failed to query database: Error: %s\n", mysql_error(&mysql)); return 1; } MYSQL_RES *result = mysql_store_result(&mysql); MYSQL_ROW row; json_object *jobj = json_object_new_array(); // 創(chuàng)建json數(shù)組 while (row = mysql_fetch_row(result)) // 將查詢結(jié)果轉(zhuǎn)化為json格式 { json_object *jobj_row = json_object_new_object(); json_object_object_add(jobj_row, "id", json_object_new_string(row[0])); json_object_object_add(jobj_row, "name", json_object_new_string(row[1])); json_object_object_add(jobj_row, "age", json_object_new_int(atoi(row[2]))); json_object_array_add(jobj, jobj_row); } // 輸出json格式數(shù)據(jù) printf("%s", json_object_to_json_string(jobj)); // 釋放資源 mysql_free_result(result); mysql_close(&mysql); json_object_put(jobj); return 0; }
以上是將數(shù)據(jù)庫中的數(shù)據(jù)轉(zhuǎn)換成json格式的c語言代碼,通過這段代碼,可以將數(shù)據(jù)庫中的數(shù)據(jù)轉(zhuǎn)換成json格式,以便用于數(shù)據(jù)交互和處理。