#import "c:/program files/common files/system/ado/msado15.dll" / no_namespace / rename ("EOF", "adoEOF") #include <iostream> using namespace std; class ADOConn { public: ::_ConnectionPtr m_pConnection; ::_RecordsetPtr m_pRecordset; public: ADOConn(void){} //初始化-连接数据库 void OnInitADOConn(); //执行查询,返回结果集 ::_RecordsetPtr & GetRecordSet(_bstr_t bstrSQL); //执行sql语句,更新数据库 bool ExecuteSQL(_bstr_t bstrSQL); void ExitConnect(); }; void ADOConn::OnInitADOConn() { ::CoInitialize(NULL);// 初始化OLE/COM库环境 ,为访问ADO接口做准备 //AfxOleInit();//used in MFC HRESULT hr; try { hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象 //_bstr_t strConnect="driver=sql server;server=(local);Provide=SQLOLEDB;Data Source=SHL;Initial Catalog=CutwordSet;User ID=;Password=;"; _bstr_t strConnect="driver={sql server};server=(local);uid=sa;pwd=5201314;database=ShoppingDB"; hr = m_pConnection->Open( strConnect,"", "", adModeUnknown); if(SUCCEEDED(hr)) cout<<endl; cout<<"连接数据库sucess"<<endl; } catch(_com_error e)///捕捉异常 { //CString errormessage; //errormessage.Format("连接数据库失败!/r/n错误信息:%s",e.ErrorMessage()); //AfxMessageBox(errormessage);///显示错误信息 cout<<"连接数据库失败!/r/n错误信息:"<<e.Description()<<endl; } } _RecordsetPtr & ADOConn::GetRecordSet(_bstr_t bstrSQL) { try { //连接数据库,如果connection对象为空,则重新连接数据库 if(m_pConnection==NULL) OnInitADOConn(); //创建记录集对象 m_pRecordset.CreateInstance(_uuidof(Recordset)); m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText); m_pRecordset->MoveFirst(); while(!m_pRecordset->adoEOF) { string vID = (char*)(_bstr_t)m_pRecordset->GetCollect("Desn"); cout<<vID.c_str()<<endl; //移动到下一个数据 m_pRecordset->MoveNext(); } } catch(_com_error e) { cout<<e.Description()<<endl; } //返回记录集 return m_pRecordset; } bool ADOConn::ExecuteSQL(_bstr_t bstrSQL) { try { //是否已经连接数据库 if(m_pConnection ==NULL) OnInitADOConn(); m_pConnection->Execute(bstrSQL,NULL,adCmdText); return true; } catch(_com_error e) { //AfxMessageBox(e.Description()); cout<<e.Description()<<endl; return false; } } void ADOConn::ExitConnect() { //关闭记录集和连接 if(m_pRecordset !=NULL) m_pRecordset->Close(); m_pConnection->Close(); //释放环境 ::CoUninitialize();//关闭ole/com库,释放资源 } int main() { ADOConn conn; conn.OnInitADOConn(); conn.GetRecordSet("select * from Category"); }