VC++用ADO方式连接数据库

      计算机与编程 2007-10-1 4:58:00

1、文件头声明

#import"C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
#include <adoid.h>
#include "icrsint.h"

2、连接数据库

     _ConnectionPtr pConn;
     _RecordsetPtr pRst;
     try
     {
      CoInitialize(NULL);
      _ConnectionPtr pConn(__uuidof(Connection));
      _RecordsetPtr pRst(__uuidof(Recordset));
    
      pConn->ConnectionString="Provider=SQLOLEDB.1;Password=sa;Persist Security Info=False;User ID=sa;Initial Catalog=Cadastru";
      pConn->Open("","","",adConnectUnspecified);
      pRst=pConn->Execute("select * from att_cadastru where zdbsh='"+_bstr_t(strDah)+"'",NULL,adCmdText);

      while(!pRst->adoEOF)
      {
      m_ZDBH=(char *)(_bstr_t)(pRst->GetCollect("ZDBH"));

      pRst->MoveNext();
      
      }
      
     }
     catch(_com_error&e)
     {
      AfxMessageBox(e.ErrorMessage());
     }

3、关闭连接

     //pRst->Close();
     //pConn->Close();
     //pRst.Release();
     //pConn.Release();
     CoUninitialize();
=============================================================================
BOOL CMaterial_MISApp::InitInstance()
{
 AfxEnableControlContainer();
   
 Enable3dControls(); // Call this when linking to MFC statically
    
 // Init Login Count
 m_iLoginCount = 0;
 
 // 创建ADO连接对象
 if( FAILED(::CoInitialize(NULL)) )
 {
     AfxMessageBox("ADO Init failed");
  return false;
 }
 try
 {
  ADOConn.CreateInstance(__uuidof(Connection));
  ADOConn->Open("DSN=Material_MIS;Provider=MSDASQL","sa","sa", adConnectUnspecified);
 }
 // 捕捉例外
 catch(_com_error &e)
 {
  CString err;
  err.Format("%s", (char*)(e.Description()) );
  AfxMessageBox(err);
 }
 catch(...)
 {
  AfxMessageBox("Unknown Error...");
 }
 
 // 初始化ADO记录集
 m_pADOSet.CreateInstance(__uuidof(Recordset));

标签集:TAGS:
回复Comments() 点击Count()
喜欢就顶一下

回复Comments

{commentauthor}
{commentauthor}
{commenttime}
{commentnum}
{commentcontent}
作者:
{commentrecontent}