有关编译、配置详见:http://hi.baidu.com/%D4%AA%C5%F32007/blog/item/3990ecd7d41264c2a144df9e.html
/**********************************************************
** 操作系统:64位win7
** 编译器:vs2005
** PostgreSQL 9.1.3,32位,ODBC驱动已在odbcad32中添加
**********************************************************/
#import "C:\Windows\SysWOW64\msado15.dll" no_namespace rename("EOF","adoEOF")
#include <iostream>
using namespace std;
int main()
{
::CoInitialize(NULL); //初始化OLE/COM库环境
/*********连接数据库*********/
_ConnectionPtr m_pConnection;
HRESULT hr;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象
if(SUCCEEDED(hr))
{
hr = m_pConnection->Open("Data Source=PostgreSQL35W","postgres","root", adModeUnknown);
}
}
catch(_com_error e)
{
cout<<"连接数据库失败!\r\n错误信息: "<<e.ErrorMessage()<<endl;
return -1;
}
/*********操作数据库表*********/
_RecordsetPtr m_pRecordset;
try
{
hr = m_pRecordset.CreateInstance("ADODB.Recordset");
if(SUCCEEDED(hr))
{
m_pRecordset->Open("SELECT * FROM test",_variant_t((IDispatch*)m_pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);
while(!m_pRecordset->adoEOF)
{
cout<< (_bstr_t)m_pRecordset->GetCollect("name")<<" "<<(_bstr_t)m_pRecordset->GetCollect("age")<<endl;
m_pRecordset->MoveNext();
}
}
}
catch(_com_error e)
{
cout<<"读取数据库失败!\r\n错误信息: "<<e.ErrorMessage()<<endl;
}
//释放资源
m_pRecordset->Close();
m_pConnection->Close();
m_pRecordset->Release();
m_pConnection->Release();
//释放COM资源,否则会有内存泄露
::CoUninitialize();
getchar();
return 0;
}