欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

c 查詢數(shù)據(jù)庫(kù)并返回json數(shù)據(jù)庫(kù)

在C語(yǔ)言中,查詢數(shù)據(jù)庫(kù)并且返回JSON格式的數(shù)據(jù),需要使用第三方庫(kù)來操作數(shù)據(jù)庫(kù)和JSON。下面是使用libmysqlclient連接MySQL數(shù)據(jù)庫(kù)和json-c庫(kù)生成JSON數(shù)據(jù)的例子。

#include<mysql.h>
#include<json-c/json.h>
int main(){
MYSQL mysql;
char* host = "localhost";
char* user = "root";
char* password = "***";
char* dbname = "test_db";
unsigned int port = 3306;
mysql_init(&mysql);
MYSQL* pconn = mysql_real_connect(&mysql, host, user, password, dbname, port, NULL, 0);
if(pconn == NULL){
fprintf(stderr, "mysql connect error:%s\n", mysql_error(&mysql));
return -1;
}
MYSQL_RES* presult = NULL;
char* sql = "select * from user";
int ret = mysql_real_query(pconn, sql, strlen(sql));
if(ret){
fprintf(stderr, "mysql query error:%s\n", mysql_error(pconn));
return -1;
}
presult = mysql_store_result(pconn);
MYSQL_ROW row;
cJSON* pjson_root = cJSON_CreateArray();
while((row = mysql_fetch_row(presult))){
cJSON* p_json_item = cJSON_CreateObject();
cJSON_AddItemToObject(p_json_item, "id", cJSON_CreateNumber(atoi(row[0])));
cJSON_AddItemToObject(p_json_item, "name", cJSON_CreateString(row[1]));
cJSON_AddItemToObject(p_json_item, "age", cJSON_CreateNumber(atoi(row[2])));
cJSON_AddItemToArray(pjson_root, p_json_item);
}
char* json_str = cJSON_Print(pjson_root);
printf("%s\n", json_str);
cJSON_Delete(pjson_root);
mysql_free_result(presult);
mysql_close(pconn);
return 0;
}

在以上代碼中,連接數(shù)據(jù)庫(kù)使用了mysql_init()、mysql_real_connect()函數(shù),查詢使用了mysql_real_query()和mysql_store_result()函數(shù),生成JSON數(shù)據(jù)使用json-c庫(kù)中的API。