VC操作ADO的基本流程

来源:互联网 发布:知乎 智能晾衣架 编辑:程序博客网 时间:2024/05/01 09:05

VC++ ADO操作数据库方法步骤

大致步骤:

1,      引入ADO库定义文件,初始化COM环境

2,      初始化connection指针,连接数据库并打开

3,      利用已经建立好的连接,通过connection,command或者recorder对象操作数据库,对数据进行查询,处理等操作

4,      使用完毕后,关闭数据库,释放指针,并注释COM

 

 

示例程序如下:

#include "stdafx.h"

#include "iostream"

#include "string"

#include "vector"

#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")

using namespace std;

 

int _tmain(int argc, _TCHAR* argv[])

{

     CoInitialize(NULL); //初始化COM环境

     _ConnectionPtr pMyConnect(__uuidof(Connection));//定义连接对象并实例化对象

     _RecordsetPtr pRst(__uuidof(Recordset));//定义记录集对象并实例化对象

         try

     {

        /*打开数据库access2007 */

       pMyConnect->Open("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=xtreme.accdb;Persist Security Info=False;","","",adModeUnknown);

     } catch (_com_error &e)

     {

         cout<<"数据库初始化错误"<<endl;

         cout<<e.Description()<<endl;

         cout<<e.HelpFile()<<endl;

         return 0;

     }

     cout<<"连接成功"<<endl;

    

     try

     {

         pRst=pMyConnect->Execute("select * from Employee",NULL,adCmdText);

         if(!pRst->BOF)

              pRst->MoveFirst();

          else

          {

              cout<<"表内数据为空"<<endl;

               return 0;

          }

         vector<_bstr_t> column_name;

/*存储表的所有列名*/

         for(int i=0; i< pRst->Fields->GetCount();i++)

         {

              cout<<pRst->Fields->GetItem(_variant_t((long)i))->Name<<endl;

              column_name.push_back(pRst->Fields->GetItem(_variant_t((long)i))->Name);

         }

 

/*对表进行遍历访问*/

         while(!pRst->adoEOF)

         {

              vector<_bstr_t>::iterator iter=column_name.begin();

              for(iter;iter!=column_name.end();iter++)

              {

                   if(pRst->GetCollect(*iter).vt !=VT_NULL)

                   {

                       cout<<(_bstr_t)pRst->GetCollect(*iter)<<endl;

                   }

                   else

                       cout<<"NULL"<<endl;

              }       

              pRst->MoveNext();//关闭记录集

              cout<<endl;

         }

     }catch(_com_error &e)

     {

         cout<<e.Description()<<endl;

         cout<<e.HelpFile()<<endl;

         return 0;

    }

 

/*关闭数据库并释放指针*/

  try

     {

         pRst->Close();     //关闭记录集

         pMyConnect->Close();//关闭数据库

         pRst.Release();//释放记录集对象指针

         pMyConnect.Release();//释放连接对象指针

     }catch(_com_error &e)

     {

         cout<<e.Description()<<endl;

         cout<<e.HelpFile()<<endl;

         return 0;

     }

 

     CoUninitialize(); //释放COM环境

    return 0;

}

说明:

     本程序是在vs2008和access2007上编译通过的,如果有编译问题,可能因版本不同引起一些问题。

     连接字符串因数据源不同而不同,所以因情况而变,可以直接连接ODBC的数据源,也可以直接连接其提供驱动的数据源。

     数据的读取仅仅局限于一般的数据类型,象access里面的超链接数据类型和OLE对象数据是无法通过一般方法读取的,需要特别的方法来读取,本程序示例暂不做描述,详情见后文。
原创粉丝点击