1、已创建MySQL数据库employeedb,数据库中有如下所示的employeetb表。
2、在使用ADO对象之前,必须在工程的Stdafx.h文件里用直接引入符号#import引入
ADO库文件,以使编译器能够正确编译。代码如下:
#import "D:\Program Files\Common Files\System\ado\msado15.dll"no_namespace rename("EOF","adoEOF") //我的系统是装在D盘
3、程序代码如下:
// ADO_OBJECT.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "ADO_OBJECT.h"
#include "MainFrm.h"
#include "ADO_OBJECTDoc.h"
#include "ADO_OBJECTView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/
// CADO_OBJECTApp
BEGIN_MESSAGE_MAP(CADO_OBJECTApp, CWinApp)
//{{AFX_MSG_MAP(CADO_OBJECTApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
// Standard file based document commands
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
// Standard print setup command
ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()
/
// CADO_OBJECTApp construction
CADO_OBJECTApp::CADO_OBJECTApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/
// The one and only CADO_OBJECTApp object
CADO_OBJECTApp theApp;
/
// CADO_OBJECTApp initialization
BOOL CADO_OBJECTApp::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
// Change the registry key under which our settings are stored.
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization.
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
LoadStdProfileSettings(); // Load standard INI file options (including MRU)
// Register the application's document templates. Document templates
// serve as the connection between documents, frame windows and views.
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CADO_OBJECTDoc),
RUNTIME_CLASS(CMainFrame), // main SDI frame window
RUNTIME_CLASS(CADO_OBJECTView));
AddDocTemplate(pDocTemplate);
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Dispatch commands specified on the command line
if (!ProcessShellCommand(cmdInfo))
return FALSE;
// The one and only window has been initialized, so show and update it.
AfxOleInit();//初始化COM环境
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
return TRUE;
}
/
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
// No message handlers
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
// App command to run the dialog
void CADO_OBJECTApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
/
// CADO_OBJECTApp message handlers
int CADO_OBJECTApp::ExitInstance()
{
// TODO: Add your specialized code here and/or call the base class
::CoUninitialize();//释放对象
return CWinApp::ExitInstance();
}
// ADO_OBJECTView.cpp : implementation of the CADO_OBJECTView class
//
#include "stdafx.h"
#include "ADO_OBJECT.h"
#include "ADO_OBJECTDoc.h"
#include "ADO_OBJECTView.h"
#include "AdoDll.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/
// CADO_OBJECTView
IMPLEMENT_DYNCREATE(CADO_OBJECTView, CView)
BEGIN_MESSAGE_MAP(CADO_OBJECTView, CView)
//{{AFX_MSG_MAP(CADO_OBJECTView)
ON_COMMAND(ID_DLL, OnDll)
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
/
// CADO_OBJECTView construction/destruction
CADO_OBJECTView::CADO_OBJECTView()
{
// TODO: add construction code here
}
CADO_OBJECTView::~CADO_OBJECTView()
{
}
BOOL CADO_OBJECTView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
/
// CADO_OBJECTView drawing
void CADO_OBJECTView::OnDraw(CDC* pDC)
{
CADO_OBJECTDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
}
/
// CADO_OBJECTView printing
BOOL CADO_OBJECTView::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CADO_OBJECTView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CADO_OBJECTView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/
// CADO_OBJECTView diagnostics
#ifdef _DEBUG
void CADO_OBJECTView::AssertValid() const
{
CView::AssertValid();
}
void CADO_OBJECTView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CADO_OBJECTDoc* CADO_OBJECTView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CADO_OBJECTDoc)));
return (CADO_OBJECTDoc*)m_pDocument;
}
#endif //_DEBUG
/
// CADO_OBJECTView message handlers
void CADO_OBJECTView::OnDll()
{
// TODO: Add your command handler code here
CAdoDll dlg;
dlg.DoModal();
}
// AdoDll.cpp : implementation file
//
#include "stdafx.h"
#include "ADO_OBJECT.h"
#include "AdoDll.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/
// CAdoDll dialog
CAdoDll::CAdoDll(CWnd* pParent /*=NULL*/)
: CDialog(CAdoDll::IDD, pParent)
{
//{{AFX_DATA_INIT(CAdoDll)
m_num = _T("");
m_sala = 0;
m_name = _T("");
m_dep = _T("");
//}}AFX_DATA_INIT
}
void CAdoDll::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAdoDll)
DDX_Control(pDX, IDC_LIST1, m_list);
DDX_Text(pDX, IDC_EDIT_NUM, m_num);
DDX_Text(pDX, IDC_EDIT_SALA, m_sala);
DDX_Text(pDX, IDC_EDIT_NAME, m_name);
DDX_Text(pDX, IDC_EDIT_DEP, m_dep);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAdoDll, CDialog)
//{{AFX_MSG_MAP(CAdoDll)
ON_BN_CLICKED(IDC_BUTTON_ADD, OnButtonAdd)
ON_BN_CLICKED(IDC_BUTTON_DEL, OnButtonDel)
ON_BN_CLICKED(IDC_BUTTON_LOAD, OnButtonLoad)
ON_BN_CLICKED(IDC_BUTTON_MOD, OnButtonMod)
ON_WM_DESTROY()
ON_LBN_SELCHANGE(IDC_LIST1, OnSelchangeList1)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/
// CAdoDll message handlers
void CAdoDll::OnButtonAdd()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
if(m_list.GetCount()==0||m_num==""||m_name=="")
{AfxMessageBox("the input data is not complete!");return;}
try
{
m_pRecordset->AddNew();
m_pRecordset->PutCollect("Fnumber",(_variant_t)m_num);
m_pRecordset->PutCollect("Fname",(_variant_t)m_name);
m_pRecordset->PutCollect("Fdepartment",(_variant_t)m_dep);
m_pRecordset->PutCollect("Fsalary",(_variant_t)(long)m_sala);//_variant_t 结构里int 型定义为long 型
m_pRecordset->Update();
AfxMessageBox("add successfully!");
OnButtonLoad() ;// refresh the list
}
catch(_com_error * e)
{
AfxMessageBox(e->ErrorMessage());
}
}
void CAdoDll::OnButtonDel()
{
// TODO: Add your control notification handler code here
if(m_list.GetCount()==0)
{AfxMessageBox("no data to delete!");return;}
else
if(m_list.GetCurSel()<0||m_list.GetCurSel()>m_list.GetCount())
m_list.SetCurSel(0);
try
{
m_pRecordset->Delete(adAffectCurrent);
m_pRecordset->Update();
int n=m_list.GetCurSel();
m_list.DeleteString(n); //delete the current value
if(n==0&&(m_list.GetCount()!=0))
m_list.SetCurSel(n);
else if(m_list.GetCount()!=0)
m_list.SetCurSel(n-1);
OnSelchangeList1();
//OnSelChangeList1();// move the pointer
}
catch(_com_error * e)
{
AfxMessageBox(e->ErrorMessage());
}
}
void CAdoDll::OnButtonLoad()
{
// TODO: Add your control notification handler code here
_variant_t num;
m_list.ResetContent();
try
{
if(!m_pRecordset->BOF)
m_pRecordset->MoveFirst();
else
{AfxMessageBox("no data in the table");return;}
while(!m_pRecordset->adoEOF)
{
num=m_pRecordset->GetCollect("Fnumber");
if(num.vt !=VT_NULL)
m_list.AddString((LPCSTR)_bstr_t(num));
m_pRecordset->MoveNext();
}
m_list.SetCurSel(0); //第一项
OnSelchangeList1();
}
catch(_com_error * e)
{
AfxMessageBox(e->ErrorMessage());
}
}
void CAdoDll::OnButtonMod()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
//UpdateBatch(adAffectAll);
if(m_list.GetCount()==0||m_num==""||m_name=="")
{AfxMessageBox("the input data is not complete!");return;}
else
if(m_list.GetCurSel()<0||m_list.GetCurSel()>m_list.GetCount())
m_list.SetCurSel(0);
try
{
m_pRecordset->PutCollect("Fnumber",_variant_t(m_num));
m_pRecordset->PutCollect("Fname",_variant_t(m_name));
m_pRecordset->PutCollect("Fdepartment",_variant_t(m_dep));
m_pRecordset->PutCollect("Fsalary",(_variant_t)(long)m_sala);
m_pRecordset->Update();
int n=m_list.GetCurSel();
OnButtonLoad() ;
m_list.SetCurSel(n);
OnSelchangeList1();
//OnSelChangeList1();// move the pointer
}
catch(_com_error * e)
{
AfxMessageBox(e->ErrorMessage());
}
}
BOOL CAdoDll::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
_variant_t value;
m_list.ResetContent();
m_pConnection.CreateInstance(_uuidof(Connection));
m_pRecordset.CreateInstance(_uuidof(Recordset));
try{
CString strConnect= "DRIVER={MySQL ODBC 5.3 ANSI Driver};SERVER=127.0.0.1;UID=root;PWD=226;DATABASE=employeedb;CharSet=gbk;";
m_pConnection->Open((_bstr_t)strConnect,"","",adModeUnknown);
m_pRecordset->Open("select * from employeetb",m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
}
catch(_com_error * e)
{
AfxMessageBox(e->ErrorMessage());
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CAdoDll::OnDestroy()
{
CDialog::OnDestroy();
// TODO: Add your message handler code here
if(m_pRecordset!=NULL)
m_pRecordset->Close();
m_pConnection->Close();
m_pRecordset=NULL;
m_pConnection=NULL;
}
void CAdoDll::OnSelchangeList1()
{
// TODO: Add your control notification handler code here
int curSel=m_list.GetCurSel();
_variant_t va,vaIndex;
if(curSel<0) return;
try
{
m_pRecordset->MoveFirst();
m_pRecordset->Move(long(curSel));
va=m_pRecordset->GetCollect("Fnumber");
if(va.vt!=VT_NULL)
m_num=(LPCSTR)_bstr_t(va);
va=m_pRecordset->GetCollect("Fname");
if(va.vt!=VT_NULL)
m_name=(LPCSTR)_bstr_t(va);
va=m_pRecordset->GetCollect("Fdepartment");
if(va.vt!=VT_NULL)
m_dep=(LPCSTR)_bstr_t(va);
va=m_pRecordset->GetCollect("Fsalary");
m_sala=(short)(va);
UpdateData(false);
}
catch(_com_error * e)
{AfxMessageBox(e->ErrorMessage());}
}
3、运行效果如下: