C++读取配置文件.txt连接数据库

本文介绍了一种从本地txt文件读取数据库配置信息的方法,并使用C++实现通过mysql_init和mysql_real_connect函数连接MySQL数据库的过程。文章详细展示了如何解析txt文件中的配置项,如url、username、password等,以及如何利用这些信息建立数据库连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值