|
|
#include <iostream.h> #import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename ("EOF", "adoEOF")
int main(){
//使用ADO连接数据库... //--------------------------------------------------------------------------------- _ConnectionPtr m_pConnection;
CoInitialize(NULL); m_pConnection.CreateInstance(__uuidof(Connection));
// 在ADO操作中建议语句中要常用try...catch()来捕获错误信息, // 因为它有时会经常出现一些想不到的错误。 try { // 打开本地Access库db1.mdb m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb","","",adModeUnknown); } catch(_com_error e) { cout<<"数据库连接失败,确认数据库db1.mdb是否在当前路径下!"<<endl; return FALSE; } //------------------------------------------------------------------------------------- //建立数据集 //------------------------------------------------------------------------------------- _RecordsetPtr m_pRecordset; m_pRecordset.CreateInstance(__uuidof(Recordset));
// 在ADO操作中建议语句中要常用try...catch()来捕获错误信息, // 因为它有时会经常出现一些意想不到的错误。 try { m_pRecordset->Open("SELECT * FROM Home2", m_pConnection.GetInterfacePtr(), // 获取库接库的IDispatch指针 adOpenDynamic, adLockOptimistic, adCmdText); } catch(_com_error *e) { //AfxMessageBox(e->ErrorMessage()); cout<<e->ErrorMessage()<<endl; }
//-------------------------------------------------------------------------------------- //读取数据 //-------------------------------------------------------------------------------------- _variant_t var; char *strID,*strX,*strY; float X,Y; try { if(!m_pRecordset->BOF) m_pRecordset->MoveFirst(); else { cout<<"表内数据为空"<<endl; return 1; } // 读入库中各字段并加入列表框中 while(!m_pRecordset->adoEOF) { var = m_pRecordset->GetCollect("ID"); if(var.vt != VT_NULL) strID= _com_util::ConvertBSTRToString((_bstr_t)var); //_variant_t转字符串 var = m_pRecordset->GetCollect("X"); if(var.vt != VT_NULL) strX=_com_util::ConvertBSTRToString((_bstr_t)var); var = m_pRecordset->GetCollect("Y"); if(var.vt != VT_NULL) strY=_com_util::ConvertBSTRToString((_bstr_t)var); cout<<strID<<"is"<<strX<<" "<<strY<<endl; m_pRecordset->MoveNext(); } } catch(_com_error *e) { cout<<e->ErrorMessage()<<endl; }
//-------------------------------------------------------------------------------------- //关闭数据集 m_pRecordset->Close(); m_pRecordset = NULL; //-------------------------------------------------------------------------------------- //关闭数据库连接 //-------------------------------------------------------------------------------------- if(m_pConnection->State) m_pConnection->Close(); m_pConnection= NULL; return 0; }
以上都是源代码部分,有个问题很奇怪,我数据库原来起的名字是position,可就是连不上去,我随便换了个叫Home2的就行了,不知道是怎么回事?
|
|