vs2005+vc8+ado

导入ADO接口

位置:stdafx.h

 

#import  " C:Program FilesCommon FilesSystemadomsado15.dll "  no_namespace rename( " EOF " , " adoEOF " ) rename( " BOF " , " adoBOF " )

定义

位置:class Ctest2App

 

    _ConnectionPtr m_pConn;
    _RecordsetPtr m_pRecordset;
    _CommandPtr m_pComm;

 

用Connection对象连接数据库

位置:BOOL Ctest2App::InitInstance()

 

    CoInitialize(NULL);
    
try
    
{
        
//初始化数据库连接对象
        m_pConn.CreateInstance("ADODB.Connection");
        m_pRecordset.CreateInstance(
"ADODB.Recordset");
        m_pComm.CreateInstance(
"ADODB.Command");
        
//定义数据库连接字符串
        _bstr_t Connectionstr="Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=boqing;Data Source=.";
        m_pConn
->Open(Connectionstr,"","",adModeUnknown);
    }

    
catch  (_com_error  & e)
    
{
        ::CoUninitialize();
        AfxMessageBox(e.ErrorMessage());
        
return FALSE;    
    }

 

利用Connection对象的Execute方法执行SQL命令

 

    _variant_t ra;
    m_pRecordset
= m_pConn -> Execute( " select count(*) from table1 " , & ra,adCmdText);
    _variant_t num
= m_pRecordset -> GetCollect((_variant_t)( long )( 0 ));
    CString msg;
    msg.Format(_T(
" 共有%d条记录 " ),num.lVal);
    AfxMessageBox(msg);

 

利用Command对象执行SQL命令

 

     // 关键的一句,将建立的连接赋值给他
    m_pComm -> ActiveConnection = m_pConn;
    m_pComm
-> CommandText = " select count(*) from table1 " ;
    m_pRecordset
= m_pComm -> Execute(NULL,NULL,adCmdText);
    _variant_t num
= m_pRecordset -> GetCollect((_variant_t)( long )( 0 ));
    CString msg;
    msg.Format(_T(
" 共有%d条记录 " ),num.lVal);
    AfxMessageBox(msg);

 

直接用Recordset对象进行查询取得记录集

 

    m_pRecordset -> Open( " select count(*) from table1 " ,_variant_t((IDispatch  * )m_pConn, true ),adOpenStatic,adLockOptimistic,adCmdText);
    _variant_t num
= m_pRecordset -> GetCollect((_variant_t)( long )( 0 ));
    CString msg;
    msg.Format(_T(
" 共有%d条记录 " ),num.lVal);
    AfxMessageBox(msg);

你可能感兴趣的:(vs2005+vc8+ado)