WEB开发网
开发学院软件开发VC VC++中使用ADO方式操作ACCESS数据库 阅读

VC++中使用ADO方式操作ACCESS数据库

 2009-10-07 20:29:27 来源:WEB开发网   
核心提示:三、程序代码/// ADOTest1Dlg.h : header file#if !defined(AFX_ADOTEST1DLG_H__29B385C0_02C0_4588_A8B4_D0EFBB4F578D__INCLUDED_)#define AFX_ADOTEST1DLG_H__29B385C0_02C0_45

三、程序代码

/////////////////////////////////////////////////// ADOTest1Dlg.h : header file
#if !defined(AFX_ADOTEST1DLG_H__29B385C0_02C0_4588_A8B4_D0EFBB4F578D__INCLUDED_)
#define AFX_ADOTEST1DLG_H__29B385C0_02C0_4588_A8B4_D0EFBB4F578D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CADOTest1Dlg : public CDialog
{
 // Construction
 public:
  BOOL m_bAutoSave;
  void SaveData();
  void LoadData();
  _variant_t vUserID,vUsername,vOld,vBirthday;
  BOOL m_bSuccess;
  int m_nCurrentSel;
  _RecordsetPtr m_pRecordset;
  CADOTest1Dlg(CWnd* pParent = NULL); // standard constructor
  // Dialog Data
  //{{AFX_DATA(CADOTest1Dlg)
   enum { IDD = IDD_ADOTEST1_DIALOG };
   CButton m_cDelItem;
   CButton m_cAddItem;
   CListCtrl m_userlist;
   UINT m_nUserID;
   UINT m_nOld;
   CString m_sUsername;
   COleDateTime m_tBirthday;
  //}}AFX_DATA
  // ClassWizard generated virtual function overrides
  //{{AFX_VIRTUAL(CADOTest1Dlg)
 protected:
  virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
  //}}AFX_VIRTUAL
  // Implementation
 protected:
  HICON m_hIcon;
  // Generated message map functions
  //{{AFX_MSG(CADOTest1Dlg)
   virtual BOOL OnInitDialog();
   afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
   afx_msg void OnPaint();
   afx_msg HCURSOR OnQueryDragIcon();
   virtual void OnOK();
   afx_msg void OnAdditem();
   afx_msg void OnDelitem();
   afx_msg void OnItemchangedUserlist(NMHDR* pNMHDR, LRESULT* pResult);
  //}}AFX_MSG
  DECLARE_MESSAGE_MAP()
};
#endif
////////////////////////////////////////////////////// ADOTest1Dlg.cpp : implementation file
#include "stdafx.h"
#include "ADOTest1.h"
#include "ADOTest1Dlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern CADOTest1App theApp;
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)
  //}}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()

CADOTest1Dlg::CADOTest1Dlg(CWnd* pParent /*=NULL*/)
: CDialog(CADOTest1Dlg::IDD, pParent)
{
 //{{AFX_DATA_INIT(CADOTest1Dlg)
  m_nUserID = 0;
  m_nOld = 0;
  m_sUsername = _T("");
  m_tBirthday = COleDateTime::GetCurrentTime();
 //}}AFX_DATA_INIT
 // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
 m_nCurrentSel = -1;
 m_bSuccess = FALSE;
 m_bAutoSave = TRUE;
}

void CADOTest1Dlg::DoDataExchange(CDataExchange* pDX)
{
 CDialog::DoDataExchange(pDX);
 //{{AFX_DATA_MAP(CADOTest1Dlg)
  DDX_Control(pDX, IDC_DELITEM, m_cDelItem);
  DDX_Control(pDX, IDC_ADDITEM, m_cAddItem);
  DDX_Control(pDX, IDC_USERLIST, m_userlist);
  DDX_Text(pDX, IDC_USERID, m_nUserID);
  DDX_Text(pDX, IDC_OLD, m_nOld);
  DDX_Text(pDX, IDC_USERNAME, m_sUsername);
  DDX_DateTimeCtrl(pDX, IDC_DATETIMEPICKER1, m_tBirthday);
 //}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CADOTest1Dlg, CDialog)
//{{AFX_MSG_MAP(CADOTest1Dlg)
 ON_WM_SYSCOMMAND()
 ON_WM_PAINT()
 ON_WM_QUERYDRAGICON()
 ON_BN_CLICKED(IDC_ADDITEM, OnAdditem)
 ON_BN_CLICKED(IDC_DELITEM, OnDelitem)
 ON_NOTIFY(LVN_ITEMCHANGED, IDC_USERLIST, OnItemchangedUserlist)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

BOOL CADOTest1Dlg::OnInitDialog()
{
 CDialog::OnInitDialog();
 m_cDelItem.EnableWindow(FALSE);
 ::SendMessage(m_userlist.m_hWnd, LVM_SETEXTENDEDLISTVIEWSTYLE,
 LVS_EX_FULLROWSELECT, LVS_EX_FULLROWSELECT);
 //////////为列表控件添加列//////////
 m_userlist.InsertColumn(0,"用户ID",LVCFMT_LEFT,60);
 m_userlist.InsertColumn(1,"用户名",LVCFMT_LEFT,100);
 m_userlist.InsertColumn(2,"年龄",LVCFMT_LEFT,60);
 m_userlist.InsertColumn(3,"生日",LVCFMT_LEFT,100);
 //////////读取数据库中的信息添加到列表控件///////////
 int nItem;
 _variant_t vUsername,vBirthday,vID,vOld;
 try
 {
  m_pRecordset.CreateInstance("ADODB.Recordset");
  m_pRecordset->Open("SELECT*FROM users",
  _variant_t((IDispatch*)theApp.m_pConnection,true),
  adOpenStatic,adLockOptimistic,adCmdText);
  m_bSuccess = TRUE;
  while(!m_pRecordset->adoEOF)
  {
   vID = m_pRecordset->GetCollect("ID");
   vUsername = m_pRecordset->GetCollect("username");
   vOld = m_pRecordset->GetCollect("old");
   vBirthday = m_pRecordset->GetCollect("birthday");
   nItem=m_userlist.InsertItem(0xffff,(_bstr_t)vID);
   m_userlist.SetItem(nItem,1,1,(_bstr_t)vUsername,NULL,0,0,0);
   m_userlist.SetItem(nItem,2,1,(_bstr_t)vOld,NULL,0,0,0);
   m_userlist.SetItem(nItem,3,1,(_bstr_t)vBirthday,NULL,0,0,0);
   m_pRecordset->MoveNext();
  }
 }
 catch(_com_error e)///捕捉异常
 {
  AfxMessageBox("读取数据库失败!");///显示错误信息
 }
 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
 ASSERT(IDM_ABOUTBOX < 0xF000);
 CMenu* pSysMenu = GetSystemMenu(FALSE);
 if (pSysMenu != NULL)
 {
  CString strAboutMenu;
  strAboutMenu.LoadString(IDS_ABOUTBOX);
  if (!strAboutMenu.IsEmpty())
  {
   pSysMenu->AppendMenu(MF_SEPARATOR);
   pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
  }
 }
 SetIcon(m_hIcon, TRUE); // Set big icon
 SetIcon(m_hIcon, FALSE); // Set small icon
 return TRUE; // return TRUE unless you set the focus to a control
}

void CADOTest1Dlg::OnSysCommand(UINT nID, LPARAM lParam)
{
 if ((nID & 0xFFF0) == IDM_ABOUTBOX)
 {
  CAboutDlg dlgAbout;
  dlgAbout.DoModal();
 }
 else
 {
  CDialog::OnSysCommand(nID, lParam);
 }
}

void CADOTest1Dlg::OnPaint()
{
 if (IsIconic())
 {
  CPaintDC dc(this); // device context for painting
  SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
  // Center icon in client rectangle
  int cxIcon = GetSystemMetrics(SM_CXICON);
  int cyIcon = GetSystemMetrics(SM_CYICON);
  CRect rect;
  GetClientRect(&rect);
  int x = (rect.Width() - cxIcon + 1) / 2;
  int y = (rect.Height() - cyIcon + 1) / 2;
  // Draw the icon
  dc.DrawIcon(x, y, m_hIcon);
 }
 else
 {
  CDialog::OnPaint();
 }
}

HCURSOR CADOTest1Dlg::OnQueryDragIcon()
{
 return (HCURSOR) m_hIcon;
}

void CADOTest1Dlg::OnOK()
{
 if(m_bSuccess)
 {
  m_pRecordset->Update();
  m_pRecordset->Close();
 }
 CDialog::OnOK();
}

void CADOTest1Dlg::OnAdditem()
{
 if(UpdateData())
  if(m_sUsername.GetLength()>0)
  {
   m_pRecordset->AddNew();
   m_nCurrentSel = m_userlist.InsertItem(0xffff,"");
   SaveData();///保存数据
   m_userlist.SetItemState(m_nCurrentSel,LVIS_SELECTED|LVIS_FOCUSED,LVIS_SELECTED|LVIS_FOCUSED);
   m_userlist.SetHotItem(m_nCurrentSel);
   m_userlist.SetFocus();
  }
  else
   AfxMessageBox("请输入用户名");
}

void CADOTest1Dlg::OnDelitem()
{
 m_bAutoSave = FALSE;
 if(m_nCurrentSel >= 0)
 {
  m_userlist.DeleteItem(m_nCurrentSel);
  int count = m_userlist.GetItemCount();
  if(count <= m_nCurrentSel)
   m_nCurrentSel = count-1;
   m_pRecordset->Delete(adAffectCurrent);
   m_pRecordset->MoveNext();
   LoadData();
   m_userlist.SetItemState(m_nCurrentSel,LVIS_SELECTED|LVIS_FOCUSED,LVIS_SELECTED|LVIS_FOCUSED);
   m_userlist.SetFocus();
 }
 m_bAutoSave = TRUE;
}

//////////在选择列表框的时候调用///////////////////
void CADOTest1Dlg::OnItemchangedUserlist(NMHDR* pNMHDR, LRESULT* pResult)
{
 NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
 if(pNMListView->uNewState&LVIS_SELECTED)
 {
  UpdateData();
  SaveData();///保存旧数据
  m_nCurrentSel = pNMListView->iItem;
  LoadData();///加载新数据
  m_cDelItem.EnableWindow();
 }
 *pResult = 0;
}

//////将记录集中的数据加载到编辑框/////
void CADOTest1Dlg::LoadData()
{
 m_pRecordset->Move(m_nCurrentSel,_variant_t((long)adBookmarkFirst));
 vUserID = m_pRecordset->GetCollect("ID");
 vUsername = m_pRecordset->GetCollect("username");
 vOld = m_pRecordset->GetCollect("old");
 vBirthday = m_pRecordset->GetCollect("birthday");
 m_nUserID = vUserID.lVal;
 m_sUsername = (LPCTSTR)(_bstr_t)vUsername;
 m_nOld = vOld.lVal;
 m_tBirthday = vBirthday;
 UpdateData(FALSE);
}

/////将编辑框的数据保存到记录集与列表框
void CADOTest1Dlg::SaveData()
{
 if(!m_pRecordset->adoEOF && m_nCurrentSel >= 0 && m_bAutoSave)
 {
  vUserID = (long)m_nUserID;
  vUsername = m_sUsername;
  vOld = (long)m_nOld;
  vBirthday = m_tBirthday;
  m_pRecordset->PutCollect("ID",vUserID);
  m_pRecordset->PutCollect("username",vUsername);
  m_pRecordset->PutCollect("old",vOld);
  m_pRecordset->PutCollect("birthday",vBirthday);
  m_userlist.SetItem(m_nCurrentSel,0,LVIF_TEXT,(_bstr_t)vUserID,NULL,0,0,0);
  m_userlist.SetItem(m_nCurrentSel,1,LVIF_TEXT,(_bstr_t)vUsername,NULL,0,0,0);
  m_userlist.SetItem(m_nCurrentSel,2,LVIF_TEXT,(_bstr_t)vOld,NULL,0,0,0);
  m_userlist.SetItem(m_nCurrentSel,3,LVIF_TEXT,(_bstr_t)vBirthday,NULL,0,0,0);
 }
}
////////////////////////////////////////////////////////////////////////
BOOL CADOTest1App::InitInstance()
{
 AfxEnableControlContainer();
 AfxOleInit();///初始化COM库
 HRESULT hr; ////////////连接数据库//////////////
 try
 {
  hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象
  if(SUCCEEDED(hr))
  {
   hr = m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;
   Data Source=test.mdb","","",adModeUnknown);///连接数据库
   ///上面一句中连接字串中的Provider是针对ACCESS2000环境的,
   /////对于ACCESS97,需要改为:Provider=Microsoft.Jet.OLEDB.3.51; }
  }
 }
 catch(_com_error e)///捕捉异常
 {
  CString errormessage;
  errormessage.Format("连接数据库失败!rn错误信息:%s",e.ErrorMessage());
  AfxMessageBox(errormessage);///显示错误信息
  return FALSE;
 }
 #ifdef _AFXDLL
  Enable3dControls(); // Call this when using MFC in a shared DLL
 #else
  Enable3dControlsStatic(); // Call this when linking to MFC statically
 #endif
 CADOTest1Dlg dlg;
 m_pMainWnd = &dlg;
 int nResponse = dlg.DoModal();
 if (nResponse == IDOK)
 {}
 else if (nResponse == IDCANCEL)
 {}
 return FALSE;
}

/////////////////////////////////////////////
int CADOTest1App::ExitInstance()
{
 if(m_pConnection->State)
 m_pConnection->Close(); ///如果已经打开了连接则关闭它
 return CWinApp::ExitInstance();
}

四、小结

限于篇幅ADO中的许多内容还没有介绍,如绑定方式处理记录集数据、存储过程的调用、事务处理、图象在数据库中的保存与读取、与表格控件的配合使用等。如果读者对上述内容感性认识的话,可以自行参考相关编程资料。

上一页  1 2 3 4 5 

Tags:VC 使用 ADO

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接