linux(ubuntu) mysql 内容导出到配置文件

1. 把一个数据库中的所有表的所有数据导出成配置文件(这是一个粗略的版本,其中数据都是导出成字符串的,有待完善)

#include <iostream>
#include <string>
#include <vector>
#include <mysql/mysql.h>
#include "json/json.h"
#include <fstream>

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<string> 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<string>::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;

				}
				*/
				jsonRow[field->name] = Json::Value(row1[i]);
			}	
			row1 = mysql_fetch_row( result );
			cout << *cit << endl;
			
			jsonTable.append(jsonRow);
		}
		
		
		os << jsonTable;
		os << flush;
		os.close();
	}
	
	return 0;
}



你可能感兴趣的:(linux(ubuntu) mysql 内容导出到配置文件)