通过本方法可以实现链接数据库,并进行查询。源代码中注释很完备。
//头文件
#import "msado15.dll" no_namespace rename("EOF","adoEOF")
#include<string>
#include<ICRSINT.h>
class DbHelper
{
public:
DbHelper()
{
::CoInitialize(0);//初始化com库
}
bool initConnection();
bool exeSelect(std::string sql);
private:
_ConnectionPtr connPtr;
};
//实现文件
#include"DbHelper.h"
#include<iostream>
bool DbHelper::initConnection()
{
HRESULT hr = connPtr.CreateInstance(__uuidof(Connection));//将对象指针实例化
if (FAILED(hr))
{
std::cout << "_ConnectionPtr对象指针实例化失败!" << std::endl;
return false;
}
try
{
//数据库链接字符串
connPtr->Open("Provider=SQLOLEDB.1;Password=123;Persist Security Info=True;User ID = sa; Initial Catalog = testDb; Data Source = 127.0.0.1", "", "", adModeUnknown);
}
catch (_com_error &e)
{
std::cout << "connection failed " << e.ErrorMessage() << std::endl;
return false;
}
return true;
}
bool DbHelper::exeSelect(std::string sql, _RecordsetPtr &recordPtr)
{
recordPtr = NULL;
if (FAILED(recordPtr.CreateInstance(__uuidof(Recordset))))
{
std::cout << "记录创建失败" << std::endl;
return false;
}
_bstr_t bstrSQL(sql.c_str());
try
{
recordPtr->Open(bstrSQL, connPtr.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
}
catch (_com_error &e)
{
std::cout << "查询记录结果操作失败 " << e.ErrorMessage() << std::endl;
return false;
}
return true;
}