VC中调用ADO对象访问数据库的范例

Visual C++ Code
#include "stdafx.h" #include "stdio.h"
#include
"windows.h"
#include
"string.h"
#import
"C:/Program Files/Common Files/System/ado/msado20.tlb" no_namespace rename("EOF", "adoEOF")
HRESULT ComInit();
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                    
int       nCmdShow)
{

    _ConnectionPtr pCn;
    _RecordsetPtr pRs;


    _variant_t vtEmpty;
    _variant_t vRsinfo;
   
long ccc;
   
char jj[255];
   
int j;

    ComInit();
    pCn.CreateInstance(__uuidof(Connection));
    pRs.CreateInstance(__uuidof(Recordset));

    pCn->Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C://VcADO//users.mdb","","",-1);
   
if(pCn->State==0){
        MessageBox(
0,"连接数据库失败。","连接失败",MB_OK);
    }
else{
        vtEmpty="select * from 用户信息表";
        pRs
->Open(vtEmpty, pCn.GetInterfacePtr(),adOpenStatic,adLockOptimistic,adCmdText);
        ccc
=pRs->RecordCount;
       
if(ccc>=1){
            vRsinfo=pRs->Fields->GetItem("姓名")->GetValue();
            j
=sprintf(jj,"查询到:%s",(char*)(_bstr_t)vRsinfo);
            MessageBox(
0,jj,"查询成功",MB_OK);
            pRs
->Close();
        }
else{
            MessageBox(
0,"没有查询到数据.","查询失败",MB_OK);
        }
        pCn
->Close();
    }
   
return 0;
}


//COM 使用时初始化
HRESULT ComInit()
{
    HRESULT hr
= S_OK;             // 默认返回值
    if FAILED(CoInitialize(NULL))  // COM 初始化调用
    {
        CoUninitialize();
        hr
= E_UNEXPECTED;
    }
   
return hr;
}

你可能感兴趣的:(c,数据库,Microsoft,null,Access)