在VC中使用ADO

[入库:2005年8月18日] [更新:2007年3月25日]

本文简介:选择自 floodzhu 的 blog

在vc中使用ado

  1. 导入ado类型库

    #pragma warning(disable: 4146)
    #import  "c:\program files\common files\system\ado\msado15.dll"  no_namespace rename( "eof", "adoeof" )
    #pragma warning(default: 4146)
    注:在最新的sdk中这句话编译不通过!(???)
  2. 增加自动化支持

    在cmyapp::initinstance()中加入
    if (!afxoleinit())
        return false;
  3. 以caboutdlg为例,在其中放置一个listbox控件,对应于m_list

  4. 在caboutdlg中声明

    _recordsetptr m_precordset;
    _connectionptr m_pconnection;
  5. 在oninitdialog()中建立连接

    try{
        m_pconnection.createinstance(__uuidof(connetion));
        m_pconnection.open("provider=microsoft.jet.oledb.4.0;data source=e:\\gcl6\\data\\test.mdb;",
            "","",-1);	//在"="两边莫加空格!
    catch(...)
    {
        afxmessagebox("数据库连接失败!");
    }      
  6. 打开查询,访问数据

    _variant thevalue;
    m_precordset.createinstance(__uuidof(recordset));
    m_list.resetcontent();
    try
    {
        m_precordset->open("select * from property",  //注意:m_precordset后加 . 和加 -> 功能不同
            m_pconnection.getinterfaceptr(),
            adopendynamic,
            adlockoptimistic,
            adcmdtext
            );
        while (!m_precordset->adoeof)
        {
            thevalue = m_precordset->getcollect("caption");
            if (thevalue.vt != vt_null)
                m_list.addstring((char *)_bstr_t(thevalue));
            m_precordset -> movenext();
        }
        m_precordset -> close();
    }
    catch(...)
    {
        afxmessagebox("error!");
    }
  7. 访问域

    fieldprt pfield;
    for (int i=0; i<m_precordset->fields->count-1; i++)
    {
        pfield = m_precordset->fields->getitem(long(i)));
    }
    (char *)pfield->name 即域名。
    pfield->type是数据类型
    pfield->precision是精度
    注:数值类型和货币类型的precision小于255,其余类型都是255。
  8. 枚举所有表/查询

    m_precordset = m_pconnetion->openschema(adschematable);
    while(!m_precordset->adoeof)
    {
        char ptype[40];
        strcpy(ptype, (char *)_bstr_t(m_precordset->getcollect("table_type")));
        if (!strcmp(ptype, "table"))  //"view"对应于查询
            m_precordset -> getcollect("table_name"); //得到表名(需要转化一下)
    }

本文关键:在VC中使用ADO
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top