1. 这次加了对int和varchar的处理
#include#include #include #include #include "json/json.h"#include #include using namespace std;int main(int argc, char* argv[]){ MYSQL mysql; mysql_init( &mysql ); mysql_real_connect( &mysql, "192.168.16.114", "root", "root", "test", 3306, NULL, 0 ); string sql = "show tables;"; mysql_query( &mysql, sql.c_str() ); MYSQL_RES *result = NULL; result = mysql_store_result( &mysql ); vector tables; MYSQL_ROW row = NULL; //得到所有的表 row = mysql_fetch_row( result ); while ( NULL != row ) { tables.push_back( row[0] ); cout << row[0] << endl; row = mysql_fetch_row( result ); } for(vector ::const_iterator cit = tables.begin(); cit != tables.end(); ++ cit) { sql = "select * from " + *cit; mysql_query( &mysql, sql.c_str() ); cout << sql << endl; //得到表中列的数量 result = mysql_store_result( &mysql ); MYSQL_FIELD* field = NULL; ofstream os; string tableName = *cit + ".json"; os.open( tableName.c_str() ); Json::Value jsonTable; MYSQL_ROW row1 = mysql_fetch_row( result ); int field_count = mysql_num_fields( result ); while ( NULL != row1 ) { Json::Value jsonRow; for(int i = 0; i < field_count; ++i) { field = mysql_fetch_field_direct( result, i ); switch(field->type) { case MYSQL_TYPE_TINY: cout << "MYSQL_TYPE_TINY" << endl; break; case MYSQL_TYPE_SHORT: cout << "MYSQL_TYPE_SHORT" << endl; break; case MYSQL_TYPE_BLOB: cout << "MYSQL_TYPE_BLOB" << endl; break; case MYSQL_TYPE_LONG: jsonRow[field->name] = Json::Value( atoi(row1[i]) ); cout << "MYSQL_TYPE_LONG" << endl; break; case MYSQL_TYPE_VAR_STRING: cout << "MYSQL_TYPE_VAR_STRING" << endl; jsonRow[field->name] = Json::Value( row1[i] ); break; } } row1 = mysql_fetch_row( result ); //cout << *cit << endl; jsonTable.append(jsonRow); } os << jsonTable; os << flush; os.close(); } return 0;}
上面只处理了一些两种类型 其他类型如下
MYSQL_TYPE_TINY TINYINT字段MYSQL_TYPE_SHORT SMALLINT字段MYSQL_TYPE_LONG INTEGER字段MYSQL_TYPE_INT24 MEDIUMINT字段MYSQL_TYPE_LONGLONG BIGINT字段MYSQL_TYPE_DECIMAL DECIMAL或NUMERIC字段MYSQL_TYPE_NEWDECIMAL 精度数学DECIMAL或NUMERICMYSQL_TYPE_FLOAT FLOAT字段MYSQL_TYPE_DOUBLE DOUBLE或REAL字段MYSQL_TYPE_BIT BIT字段MYSQL_TYPE_TIMESTAMP TIMESTAMP字段MYSQL_TYPE_DATE DATE字段MYSQL_TYPE_TIME TIME字段MYSQL_TYPE_DATETIME DATETIME字段MYSQL_TYPE_YEAR YEAR字段MYSQL_TYPE_STRING CHAR字段MYSQL_TYPE_VAR_STRING VARCHAR字段MYSQL_TYPE_BLOB BLOB或TEXT字段(使用max_length来确定最大长度)MYSQL_TYPE_SET SET字段MYSQL_TYPE_ENUM ENUM字段MYSQL_TYPE_GEOMETRY Spatial字段MYSQL_TYPE_NULL NULL-type字段MYSQL_TYPE_CHAR 不再重视,用MYSQL_TYPE_TINY取代