2014年3月26日17:28:15
MFC中使用ADO访问Oracle
通过执行SQL语句访问数据库。
_ConnectionPtr pConnection=NULL;//连接
_RecordsetPtr pRecordset=NULL;//记录集
::CoInitialize(NULL);
pConnection.CreateInstance(__uuidof(Connection));
pRecordset.CreateInstance(__uuidof(Recordset));
if(!pConnection->State)
{
_bstr_t strConnect =_T("Provider=MSDAORA;Data Source=ORCL;User ID=etc_ctrlr;Password=itsmoe");
CString sInfo;
try
{
pConnection->Open(strConnect, _T(""),_T(""), adModeUnknown);
sInfo.Format(_T("连接成功"));
}catch (_com_error e)
{
sInfo.Format(_T("连接失败"));
}
MessageBox(sInfo);
}
_bstr_t bstrPointSQL(L"select * from LWW_TEST");
try
{
pRecordset->Open(bstrPointSQL, pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
_variant_t var;
int nSn=0;int nX=0;int nY=0;
CString str;
while (!pRecordset->EndOfFile)
{
var = pRecordset->GetCollect(L"SN");
nSn = var.intVal;
var = pRecordset->GetCollect(L"X");
nX = var.intVal;
var = pRecordset->GetCollect(L"Y");
nY = var.intVal;
str.Format(_T("SN:%d;X:%d;Y:%d"),nSn,nX,nY);
//MessageBox(str);
pRecordset->MoveNext();
}
pRecordset->Close();
}catch (_com_error e)
{
exit(-1);
}
try
{
CString sInsert;
sInsert.Format(_T("insert into LWW_TEST (SN,x,y) values(4,4,4)"));
pConnection->Execute((_bstr_t)sInsert,NULL,adCmdText);
}catch (_com_error &e)
{
CString sInfo;
sInfo.Format(_T("添加数据失败:%s"),e.ErrorMessage());
MessageBox(sInfo);
exit(-1);
}
try
{
CString sInsert;
sInsert.Format(_T("update LWW_TEST set x=5 where SN=4"));
pConnection->Execute((_bstr_t)sInsert,NULL,adCmdText);
}catch (_com_error &e)
{
CString sInfo;
sInfo.Format(_T("更新数据失败:%s"),e.ErrorMessage());
MessageBox(sInfo);
exit(-1);
}
if (pRecordset->State)
pRecordset->Close();
if(pConnection->State)
pConnection->Close();
::CoUninitialize();