MFC中使用ADO访问Oracle数据库

来源:互联网 发布:申请淘宝020线下安装 编辑:程序博客网 时间:2024/05/01 20:00

操作系统:win7 64bit

软件环境:VS2012,

      本地客户端使用Oracle 11g 64bit

      远程服务器端使用Oracle 11g 32bit


1、  导入msado15.dll动态链接库


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


2、初始化Com组件


AfxEnableControlContainer();AfxOleInit();                              //初始化COM库

3、连接字符串


CString strConnect;strConnect.Format("Provider=OraOLEDB.Oracle.1;Password=%s;PersistSecurity Info=True;User ID=%s;\DataSource=\"(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST =%s)\(PORT = %s)) )(CONNECT_DATA= (SID = %s)))\"",m_sPwd, m_sUid, m_sHost, m_sPort, m_sSid);


创建两个对象:

_ConnectionPtrm_pConnection;_RecordsetPtrm_pRecordset;

4、连接数据库


try{         ::CoInitialize(NULL);                                                  //初始化com环境(必须,否则提示异常)         m_pConnection.CreateInstance(__uuidof(Connection));         m_pConnection->ConnectionTimeout= 10;               // 设置连接超时10秒         m_pConnection->Open(_bstr_t(LPCTSTR(strConnect)),"","",adModeUnknown);         m_pConnection->CursorLocation= adUseClient;  //设置使用客户端连接}catch (_com_error e){         AfxMessageBox(e.Description());         return FALSE;}catch(...){         AfxMessageBox("数据库连接失败!");         return FALSE;}

 Tips:因为本地客户端使用的是64bit版本的Oracle,所以如果编译的时候选择win32,就会抛出异常。说是检查安装。所以要选择使用生成x64版本!!这一点要特别注意!!!

 

5、读写数据库

  如果上述1-4步骤都正确无误,那么读写数据库就是相对比较简单的工作了。

m_pRecordset.CreateInstance("ADODB.Recordset");//创建Recordset实例strSQL="select * from robin";try{m_pRecordset->Open((_variant_t)strSQL,(IDispatch*)theApp.m_pConnection,adOpenDynamic,adLockOptimistic,adCmdText);}catch (_com_error* e){    AfxMessageBox(e->ErrorMessage());}try{    nFieldsCount=m_pRecordset->GetFields()->Count;}catch (_com_error* e){    AfxMessageBox(e->ErrorMessage());//弹出错误对话框}

接下来就可以通过m_pRecordset来获取查询语句得到的结果了。

 

 

0 0
原创粉丝点击