gsoap读取的sqlite数据库,并编写为JSON格式
这是gsoap中的一段重要代码: int SmsWBSService::run(int port) { if (soap_valid_socket(this->master) || soap_valid_socket(bind(NULL,port,100))) { for (;;) { if (!soap_valid_socket(accept()) || serve()) return this->error; soap_destroy(this); soap_end(this); } } else return this->error; return SOAP_OK; } 这段代码是用C++编写的gsoap服务器,用来监听客户端,接受客户端的请求。
如题,这里需要了解sqlite的几个重要接口函数: int sqlite3_prepare( int sqlite3_step(sqlite3_stmt*); 如果执行成功会返回SQLITE_DONE,如果查询有结果会返回SQLITE_ROW,并可以通过API获取结果中的第一行数据,需要获取下一行数据可以再次调用sqlite3_step直到返回SQLITE_DONE表示后面没有数据了 const unsigned char *sqlite3_column_text(sqlite3_stmt*,int iCol); 该函数返回字符串,其中sqlite3_column_text输出的字符串使用UTF8编码 int sqlite3_column_count(sqlite3_stmt*); 获得列数,调用成功时返回数据库的列数 这里主要有两个方面:数据库的遍历和字符的拼接。 通过调用sqlite3_step(sqlite3_stmt*)和const unsigned char *sqlite3_column_text(sqlite3_stmt*,int iCol);可以完成对数据库的遍历,每次调用结束后用sprintf将拼接得到的字符串,可以得到一行的数据,将每行的数据拼接就可以得到整个数据库,
int webService::get_cof_table(int contolPm,xsd__string* table) { //Read the cof_table,and send the table's content to the client. char tmp[256]; //To storage the table char column_lines[256]; sqlite3* cof_db = NULL; sqlite3_stmt *ppStmt = NULL; const char *pzTail = NULL; char* errmsg = NULL; char* sql = NULL; int rc_cof; rc_cof = sqlite3_open("cof.db",&cof_db); sql = "select * from cof_table;"; int i = 0; sqlite3_prepare_v2(cof_db,sql,strlen(sql),&ppStmt,&pzTail); int ncolcount = sqlite3_column_count(ppStmt); memset(column_lines,256); strcat(column_lines,"{"); while(sqlite3_step(ppStmt) == SQLITE_ROW) { printf("n"); //printf("0 %s",tmp); for(i = 0;i<ncolcount-1;i++) { if(i == 0) { sprintf(tmp,"{"%s":"%s",",sqlite3_column_name(ppStmt,0),sqlite3_column_text(ppStmt,0)); } else { sprintf(tmp,""%s":"%s",i),i)); } //printf("%s",tmp); strcat(column_lines,tmp); } sprintf(tmp,""%s":"%s"},i)); strncat(column_lines,tmp,strlen(tmp)); } strcpy(&column_lines[strlen(column_lines)-1],"}"); sqlite3_finalize(ppStmt); *table = column_lines; memset(column_lines,256); close(cof_db); /*table = "{"cof_table": [{"KEY":"G_lamp","KEY_VALUE":"0","KEY_DESC":"杀菌灯","KEY_LIST":"[0,1]"}, {"KEY":"FANS","KEY_DESC":"风机",1,2]"}, {"KEY":"MODULE","KEY_DESC":"净化器",1]"}] }";最终传输的格式*/ return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |