1. 程式人生 > >C++讀取配置檔案.txt連線資料庫

C++讀取配置檔案.txt連線資料庫

	mysql=mysql_init((MYSQL*)0);
	ifstream file;
	string path="D:/data.txt";
	file.open(path.c_str());
	string port1;
	string url;
	string name;
	string pass;
	string dataname;
	if(file.is_open())//開啟檔案
	{
		char tmp[1000];
		while(!file.eof())//迴圈讀取每一行
		{
			file.getline(tmp,1000);
			string line(tmp);
			size_t pos=line.find('=');
			string tmpkey=line.substr(0,pos);//取=號之前
			
			if(tmpkey == "url")
			{
				url=line.substr(pos+1);//取=號之後
			}
			else if(tmpkey == "username")
			{
				name=line.substr(pos+1);
			}
			else if(tmpkey == "password")
			{
				pass=line.substr(pos+1);
			}
			else if(tmpkey == "dataname")
			{
				dataname=line.substr(pos+1);
			}
			else if(tmpkey == "port")
			{
				port1=line.substr(pos+1);
			}
		}
	}
	else
	{
		cout << "Connot open config file" << endl;
	}
	if(NULL!=mysql_real_connect(mysql,url.data(),name.data(),pass.data(),dataname.data(),atoi(port1.c_str()),NULL,0))
	//if(NULL!=mysql_real_connect(mysql,"127.0.0.1","root","root","newems",3306,NULL,0))
	{
		temp="連線資料庫成功";
		showStatus(temp);
	}
	else
	{
		temp="連線失敗";
		showStatus(temp);
	}
	return true;