|
关于数据库你要做的有四件事 设你新开一个工程,接着做以下: (1) 定义数据库联接串 char connectStr[]="Provider=Microsoft.Jet.OLEDB.4.0;DataSource=d:\\DBSample\\Peoples.mdb;Persist Security Info=False"; 特别注意数据库的路径,在正式的软件中,路径是要去注册表中读的,或到某个文件中去读 (2)在stdafx.h加入#include"msado15.tlh" 确保当前工程的目录下有msado15.tli,msado15.tlh两个文件 (3)在stdafx.h中确保关闭以下两行 //#include <afxdb.h> // MFC ODBC database classes //#include <afxdao.h> (4)写代码 ========================= 请你将我的工程解压到D下面,(D:\DBSample) 你可以加载我的Arx文件,运行dbtest试试看 数据库名是:Peoples.mdb,也包含在工程中了 我这个例子中只有一个函数; 怎么传例子? ///////////////////////////////////////////// // ObjectARX defined commands #include "StdAfx.h" #include "StdArx.h" char connectStr[]="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\\DBSample\\Peoples.mdb;Persist Security Info=False"; // This is command 'DBTEST' void kindbtestdbtest() { // 本函数从数据库中读取数据
_ConnectionPtr m_pConnection; HRESULT hr; CString vStr0; try { hr = m_pConnection.CreateInstance("ADODB.Connection");//Connection对象 if(SUCCEEDED(hr)) { hr =m_pConnection->Open(connectStr,"","",adModeUnknown);//数据库,office2000 ,connectStr是前面定义的全局变量 } } catch(_com_error e)///捕捉异常 { CString errormessage; errormessage.Format("连接数据库失败!\r\n错误信息:%s",e.ErrorMessage()); AfxMessageBox(errormessage);///显示错误信息 return; } char selectStr[256]; _RecordsetPtr m_pRecordset; _variant_t RecordsAffected=(long)0; _variant_t t_name,t_high,t_age; double high,age; CString temp; sprintf(selectStr,"select * from Details" );//Details是表名 m_pRecordset = m_pConnection->Execute(selectStr,&RecordsAffected,adCmdText); //上面的代码是打开数据库并获得所有的记录
//打开数据库的时候,m_pRecordset会自动指向被打开表的第一行 if (m_pRecordset->adoEOF ){//确定不是空指针 m_pConnection->Close(); return; } else { //如果不是空的记录集,遍历每一行,将每一行的姓名\身高\年纪显示出来 while( !m_pRecordset->adoEOF) { t_name = m_pRecordset->GetCollect("t_name"); temp=t_name.bstrVal; t_high = m_pRecordset->GetCollect("t_high"); high=t_high.bVal ; t_age = m_pRecordset->GetCollect("t_age"); age=t_age.bVal ; acutPrintf("\nname=%s\thigh=%f\tage=%f",temp,high,age); m_pRecordset->MoveNext ();//移动到下一行 } } m_pRecordset->Close();///关闭记录集 m_pConnection->Close();///关闭数据库连接 } |