参考:点击打开链接
_ConnectionPtr pConnection = NULL;
pConnection.CreateInstance(_uuidof(Connection));pConnection->Mode = adModeUnknown;
pConnection->ConnectionTimeout = 5;
pConnection->CommandTimeout = 5;
HRESULT hr = pConnection->Open("Provider=OraOLEDB.Oracle;Persist Security Info=True;User ID=sys;DataSource=\"(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST =192.168.5.49)(PORT = 1521)) )(CONNECT_DATA = (SID =huaneng)))\"", "test", "huangjiapeng",NULL);
if (SUCCEEDED(hr))
{
AfxMessageBox("连接数据库成功!");
}
//查询数据库
//执行命令
_RecordsetPtr pRecordset = NULL;
pRecordset.CreateInstance(_uuidof(Recordset));
hr = pRecordset->Open(_T("select * from person"), pConnection.GetInterfacePtr(), adOpenDynamic,adLockOptimistic, adCmdText);
if(SUCCEEDED(hr))
{
AfxMessageBox("查询成功");
}
else if(FAILED(hr))
{
AfxMessageBox("查询失败");
}
try
{
// 写入各字段值
CString m_Name = "hello";
CString m_Age = "98";
pRecordset->AddNew();
pRecordset->PutCollect("NAME", _variant_t(m_Name));
pRecordset->PutCollect("AGE", atol(m_Age));
pRecordset->Update();
AfxMessageBox("插入成功!");
//pRecordset->MoveFirst();
}
catch (_com_error *e)
{
AfxMessageBox(e->ErrorMessage());
}
try
{
// 假设删除第二条记录
pRecordset->MoveFirst();
pRecordset->Move(1); // 从0开始
pRecordset->Delete(adAffectCurrent); // 参数adAffectCurrent为删除当前记录
pRecordset->Update();
AfxMessageBox("删除成功!");
}
catch (_com_error *e)
{
AfxMessageBox("异常发生!");
AfxMessageBox(e->ErrorMessage());
}
//遍历结果集
pRecordset->MoveFirst();
while(!pRecordset->adoEOF)
{
_variant_t var = pRecordset->Fields->GetItem("AGE")->Value;//username
//结果有待处理
AfxMessageBox((_bstr_t)var);
pRecordset->MoveNext();
}
//关闭查询器
if(pRecordset->State)
{
pRecordset->Close();
pRecordset = NULL;
}
//关闭数据库连接
if(pConnection->State)
{
pConnection->Close();
pConnection = NULL;
}
AfxMessageBox("添加成功");
}
catch(_com_error &e)
{
AfxMessageBox(e.ErrorMessage());
}