创建基于对话框的应用程序ADO,向对话框中添加一个列表视图控件,并为其添加变量m_Grid
第一步:ADO对象的导入
在StdAfx.h头文件中:
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, bu
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__D5ADC0DF_B5B2_4973_A035_4F2F1585998F__INCLUDED_)
#define AFX_STDAFX_H__D5ADC0DF_B5B2_4973_A035_4F2F1585998F__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
#include <afxwin.h> // MFC core and standard components
#include <afxext.h> // MFC extensions
#include <afxdisp.h> // MFC Automation classes
#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h> // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT
//ADO对象的导入代码
#import"C:/Program Files/Common Files/System/ado/msado15.dll"
no_namespace rename("EOF","adoEOF")rename("BOF","adoBOF")
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__D5ADC0DF_B5B2_4973_A035_4F2F1585998F__INCLUDED_)
第二步:初始化COM环境
BOOL CADOApp::InitInstance()
{
AfxEnableControlContainer();
AfxOleInit();//或者::CoInitialize(NULL);
··················
··················
return FALSE;
}
第三步:连接数据库
在主窗口中声明指针:右击类窗口的ADODlg类,选择Add Member Variable
_RecordsetPtr m_pRecordset;
_ConnectionPtr m_pConnection;
在主窗口中声明函数:右击类窗口的ADODlg类,选择Add Member Function
void OnInitADOConn();//连接数据库
void ExitConnect();//断开数据库连接
void AddToGrid();//将数据库表中的数据显示在列表视图控件中
void CADODlg::OnInitADOConn()
{
try
{
m_pConnection.CreateInstance("ADODB.Connection");
m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=shujuku.mdb","","",adModeUnknown);
///连接数据库
//上面一句中连接字串中的Provider是针对ACCESS2000环境的,对于ACCESS97,
//需要改为:Provider=Microsoft.Jet.OLEDB.3.51;
}
catch(_com_error e)
{
CString errormessage;
errormessage.Format("连接数据库失败!/r/n错误信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);///显示错误信息
}
}
void CADODlg::ExitConnect()
{
if(m_pRecordset!=NULL)
m_pRecordset->Close();
m_pConnection->Close();
}
void CADODlg::AddToGrid()
{
OnInitADOConn();
_bstr_t bstrSQL="select * from employees order by 编号 DESC";
m_pRecordset.CreateInstance(_uuidof(Recordset));
try
{
m_pRecordset->Open(bstrSQL,m_pConnection.GetInterfacePtr(),adOpenDynamic,
adLockOptimistic,adCmdText);
while(!m_pRecordset->adoEOF)
{
m_Grid.InsertItem(0,"");
m_Grid.SetItemText(0,0,(char *)(_bstr_t)m_pRecordset->GetCollect("编号"));
m_Grid.SetItemText(0,1,(char *)(_bstr_t)m_pRecordset->GetCollect("姓名"));
m_Grid.SetItemText(0,2,(char *)(_bstr_t)m_pRecordset->GetCollect("性别"));
m_Grid.SetItemText(0,3,(char *)(_bstr_t)m_pRecordset->GetCollect("学历"));
//将记录集指针移动到下一条记录
m_pRecordset->MoveNext();
}
}
catch(_com_error e)///捕捉异常
{
AfxMessageBox("读取数据库失败!");///显示错误信息
}
//断开数据库连接
ExitConnect();
}
第四步:释放COM环境
2009-11-24