BOOL CTestProDlg::LoadTestProInfo()
{
/*创建和数据库的连接*/
CString strErr = _T("") ;
CString strUser = _T("SCOTT") ;//用户名
CString strPassword = _T("zzcan728") ;//密码
CString strDSN = _T("ORCL") ;//DSN
_CommandPtr pCommand = NULL ;
/*创建访问接口*/
try
{
HRESULT hr = m_pConn.CreateInstance(__uuidof(Connection)) ;
if (FAILED(hr))
_com_raise_error(hr, NULL) ;
CString strConnect ;
strConnect.Format(_T("Provider=OraOLEDB.Oracle.1;Password=%s;Persist Security Info=True;PLSQLRSet=1;User ID=%s;Data Source=%s"), strPassword, strUser, strDSN) ;
m_pConn->CommandTimeout = 5 ;
m_pConn->ConnectionTimeout = 5 ;
m_pConn->Open((_bstr_t)strConnect, "", "", 0) ;
if (m_pConn == NULL)
throw CString(_T("The m_pDBConnect haven't been created!")) ;
}
catch(_com_error){
strErr = _T("数据库访问接口配置错误或数据库连接失败!");
AfxMessageBox(strErr, MB_ICONEXCLAMATION) ;
return FALSE ;
}
catch(...)
{
strErr = _T("建立数据访问接口失败,程序无法继续运行!");
AfxMessageBox(strErr, MB_ICONEXCLAMATION) ;
return FALSE ;
}
/*访问数据库,执行存储过程*/
//设置传递的参数
HRESULT hr ;
CString strCommand = _T("sp_pro7") ;
_RecordsetPtr pRst ;
if (m_pConn == NULL)
AfxMessageBox(_T("数据库连接错误"), MB_ICONEXCLAMATION ) ;
//ASSERT(m_pConn == NULL) ;
if (m_pConn == NULL)
AfxMessageBox(_T("数据库连接错误"), MB_ICONEXCLAMATION ) ;
try
{
if (FAILED(hr = pRst.CreateInstance(__uuidof(Recordset))))//创建_RecordSet对象实例
_com_issue_error(hr) ;
if ((FAILED(hr = pCommand.CreateInstance(__uuidof(Command)))))//创建Command对象实例
_com_issue_error(hr) ;
pCommand->ActiveConnection = m_pConn ;//将建立的连接赋值给pCommand
pCommand->CommandType = adCmdStoredProc ;
pCommand->CommandText = (LPCTSTR)strCommand ;//命令字符串
_ParameterPtr pBookID;//BOOK ID
_ParameterPtr pBookName;//书名
_ParameterPtr pBookPublish;//出版社
pBookID.CreateInstance(__uuidof(Parameter)) ;
pBookName.CreateInstance(__uuidof(Parameter)) ;
pBookPublish.CreateInstance(__uuidof(Parameter)) ;
pBookID = pCommand->CreateParameter("id",adInteger,adParamInput,20,(_variant_t)"10");//给参数设置各属性
pCommand->Parameters->Append(pBookID);//加入到Command对象的参数集属性中
pBookName = pCommand->CreateParameter("Name",adVarChar,adParamInput,20,(_variant_t)"sanguoyanyi");
pCommand->Parameters->Append(pBookName);
pBookPublish = pCommand->CreateParameter("publish",adVarChar,adParamInput,20, (_variant_t)"安徽出版社");
pCommand->Parameters->Append(pBookPublish);
pRst = pCommand->Execute(NULL, NULL, adCmdStoredProc) ;
return TRUE ;
}
catch(_com_error e)
{
AfxMessageBox(e.Description()) ;
m_pConn->Close() ;
CoUninitialize();
return FALSE ;
}
return FALSE ;
}
仿照这个例子写的:http://blog.csdn.net/aa211314/article/details/2128756
在stdafx.h中加入#import "C:/program files/common files/system/ado/msado15.dll" no_namespace rename("EOF","adoEOF")提示windows.h重定义了在stdafx.h加入
#include <afxcoll.h>
#define _ATL_ALL_WARNINGS
在Initstance()中加入
if(!AfxOleInit())//这就是初始化COM库
{
AfxMessageBox("OLE初始化出错!");
return FALSE;
}
如何获得连接字符串:http://blog.csdn.net/zyq5945/article/details/5586423