C++连接数据库的方法

看看C++连接数据库,取结果集的方法:

1.首先,头文件加下面一行:

#import "c:\Program Files\Common Files\System\ado\msado15.dll"  no_namespace rename("EOF", "adoEOF") rename("BOF", "adoBOF") 

2.我把数据库连接写成一个函数:

_ConnectionPtr CDBase::ConectDB(void)
{
	_ConnectionPtr pConnect = NULL; 
	CoInitialize(NULL);
	if(FAILED(pConnect.CreateInstance(__uuidof(Connection))))
		return NULL; 
	CString strConnects = "Provider=SQLOLEDB; Server="+dbConn.ip+"; Database="+dbConn.database+"; uid="+dbConn.uid+"; pwd="+dbConn.pwd+";";
	_bstr_t strConnect= (_bstr_t)strConnects;
	try
	{
		pConnect->Open(strConnect, "", "", NULL); 
	}
	catch(_com_error& e){
		   MessageBoxA(0,"数据库连接失败!",0,0);
		   return NULL;
		}
	return pConnect;
}

3.sql查询结果:

void CDBase::GetDevList(void)
{
	_RecordsetPtr pRecordset = NULL; 
	if(FAILED(pRecordset.CreateInstance(__uuidof(Recordset))))  
		return ;
	_ConnectionPtr pConnect = ConectDB();
	if (!pConnect)
		return;
	try
	{   
		char* strSql = "select DevID,UDevID,Key from DEVLIST";//具体执行的SQL语句  
		pRecordset = pConnect->Execute(_bstr_t(strSql),  NULL, adCmdText);//将查询数据导入pRecordset数据容器 
		_variant_t ID,UD,Key; 
		while(!pRecordset->adoEOF)
		{
		  ID = pRecordset->GetCollect("DevID");//ID
		  UD = pRecordset->GetCollect("UDevID");
		  Key = pRecordset->GetCollect("Key");
		}
	}
	catch (CException* e)
	{
		MessageBoxA(0,"数据库操作错误!",0,0);
	}
	pConnect->Close();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值