www.pudn.com > VC++6.0 中用 ADO 存取 Access 数据库的一点总结.rar > HomeResDlg.cpp


// HomeResDlg.cpp : implementation file 
// 
 
#include "stdafx.h" 
#include "HomeRes.h" 
#include "HomeResDlg.h" 
 
#ifdef _DEBUG 
#define new DEBUG_NEW 
#undef THIS_FILE 
static char THIS_FILE[] = __FILE__; 
#endif 
 
///////////////////////////////////////////////////////////////////////////// 
// 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) 
	//}}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() 
 
///////////////////////////////////////////////////////////////////////////// 
// CHomeResDlg dialog 
 
CHomeResDlg::CHomeResDlg(CWnd* pParent /*=NULL*/) 
	: CDialog(CHomeResDlg::IDD, pParent) 
{ 
	//{{AFX_DATA_INIT(CHomeResDlg) 
	m_nHandler = -1; 
	m_strContent = _T("(无内容)"); 
	m_fMoney = 0.0f; 
	m_nType = -1; 
	//}}AFX_DATA_INIT 
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32 
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); 
	m_pConnection = NULL; 
	m_lCurID = 0; 
} 
 
void CHomeResDlg::DoDataExchange(CDataExchange* pDX) 
{ 
	CDialog::DoDataExchange(pDX); 
	//{{AFX_DATA_MAP(CHomeResDlg) 
	DDX_Control(pDX, IDC_LIST_RESULT, m_ResList); 
	DDX_Control(pDX, IDC_TREE_BUDGET, m_Tree); 
	DDX_Control(pDX, IDC_DATETIMEPICKER_TO, m_DateTo); 
	DDX_Control(pDX, IDC_DATETIMEPICKER_FROM, m_DateFrom); 
	DDX_Control(pDX, IDC_COMBO_ANATYPE, m_cobAnaType); 
	DDX_Control(pDX, IDC_COMBO_ANAHANDLER, m_cobAnaHandler); 
	DDX_Control(pDX, IDC_DATETIMEPICKER_DATE, m_Date); 
	DDX_Control(pDX, IDC_COMBO_TYPE, m_cobType); 
	DDX_Control(pDX, IDC_COMBO_HANDLE, m_cobHandle); 
	DDX_CBIndex(pDX, IDC_COMBO_HANDLE, m_nHandler); 
	DDX_Text(pDX, IDC_EDIT_CONTENT, m_strContent); 
	DDX_Text(pDX, IDC_EDIT_MONEY, m_fMoney); 
	DDX_CBIndex(pDX, IDC_COMBO_TYPE, m_nType); 
	//}}AFX_DATA_MAP 
} 
 
BEGIN_MESSAGE_MAP(CHomeResDlg, CDialog) 
	//{{AFX_MSG_MAP(CHomeResDlg) 
	ON_WM_SYSCOMMAND() 
	ON_WM_PAINT() 
	ON_WM_QUERYDRAGICON() 
	ON_BN_CLICKED(IDC_BTN_ADD, OnBtnAdd) 
	ON_WM_CLOSE() 
	ON_BN_CLICKED(IDC_BTN_MODIFY, OnBtnModify) 
	ON_BN_CLICKED(IDC_BTN_DEL, OnBtnDel) 
	ON_BN_CLICKED(IDC_BTN_ANA, OnBtnAna) 
	ON_NOTIFY(TVN_SELCHANGED, IDC_TREE_BUDGET, OnSelchangedTreeBudget) 
	//}}AFX_MSG_MAP 
END_MESSAGE_MAP() 
 
///////////////////////////////////////////////////////////////////////////// 
// CHomeResDlg message handlers 
 
BOOL CHomeResDlg::OnInitDialog() 
{ 
	CDialog::OnInitDialog(); 
 
	// Add "About..." menu item to system menu. 
 
	// IDM_ABOUTBOX must be in the system command range. 
	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); 
		} 
	} 
 
	// Set the icon for this dialog.  The framework does this automatically 
	//  when the application's main window is not a dialog 
	SetIcon(m_hIcon, TRUE);			// Set big icon 
	SetIcon(m_hIcon, FALSE);		// Set small icon 
	 
	// 
	 
	m_cobAnaType.AddString("全部类型"); 
	m_cobAnaHandler.AddString("全部人"); 
	m_cobAnaType.SetCurSel(0); 
	m_cobAnaHandler.SetCurSel(0); 
	GetSystemTime(&m_CurTime); 
	m_CurTime.wDay = 1; 
	m_DateFrom.SetTime(&m_CurTime); 
	m_CurTime.wMonth += 1; 
	m_DateTo.SetTime(&m_CurTime); 
	 
	// 初始化COM,创建ADO连接等操作 
	AfxOleInit(); 
	m_pConnection.CreateInstance(__uuidof(Connection)); 
	 
	// 在ADO操作中建议语句中要常用try...catch()来捕获错误信息, 
	// 因为它有时会经常出现一些意想不到的错误。jingzhou xu 
	try                  
	{	 
		// 打开本地Access库Demo.mdb 
		m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Home.mdb","","",adModeUnknown); 
	} 
	catch(_com_error e) 
	{ 
		AfxMessageBox("数据库连接失败,确认数据库Demo.mdb是否在当前路径下!"); 
		return FALSE; 
	}   
	 
	//从数据库中读入经手人名单和类型名单 
	_RecordsetPtr	pHandlerRecordset; 
	pHandlerRecordset.CreateInstance(__uuidof(Recordset)); 
	try 
	{ 
		pHandlerRecordset->Open("SELECT * FROM Handler",                // 查询DemoTable表中所有字段 
		m_pConnection.GetInterfacePtr(),	 // 获取库接库的IDispatch指针 
		adOpenDynamic, 
		adLockOptimistic, 
		adCmdText); 
	} 
	catch(_com_error *e) 
	{ 
		AfxMessageBox(e->ErrorMessage()); 
	}   
				 
	_variant_t var; 
	CString strName; 
	while(!pHandlerRecordset->adoEOF) 
	{ 
		var = pHandlerRecordset->GetCollect("Handler"); 
		if(var.vt != VT_NULL) 
			strName = (LPCSTR)_bstr_t(var); 
		m_cobHandle.AddString(strName);	 
		m_cobAnaHandler.AddString(strName); 
		pHandlerRecordset->MoveNext(); 
	} 
	pHandlerRecordset->Close(); 
	pHandlerRecordset.Release(); 
	pHandlerRecordset = NULL; 
	 
	////////////////////////////////////////////////////////////////////////// 
	CString strType; 
	_RecordsetPtr pTypeRecordset; 
	pTypeRecordset.CreateInstance(__uuidof(Recordset)); 
	try 
	{ 
		pTypeRecordset->Open("SELECT * FROM Type",                // 查询DemoTable表中所有字段 
			m_pConnection.GetInterfacePtr(),	 // 获取库接库的IDispatch指针 
			adOpenDynamic, 
			adLockOptimistic, 
			adCmdText); 
	} 
	catch(_com_error *e) 
	{ 
		AfxMessageBox(e->ErrorMessage()); 
	}   
 
	while(!pTypeRecordset->adoEOF) 
	{ 
		var = pTypeRecordset->GetCollect("Type"); 
		if(var.vt != VT_NULL) 
			strType = (LPCSTR)_bstr_t(var); 
		m_cobType.AddString(strType); 
		m_cobAnaType.AddString(strType); 
		pTypeRecordset->MoveNext(); 
	} 
	pTypeRecordset->Close(); 
	pTypeRecordset.Release(); 
	pTypeRecordset = NULL; 
 
 
	//读入当月的记录 
	// 
	CTime Today = CTime::GetCurrentTime(); 
	Load(Today.GetMonth(),Today.GetMonth() + 1); 
	m_nHandler = 0; 
	m_nType = 0; 
	UpdateData(FALSE); 
	return TRUE;  // return TRUE  unless you set the focus to a control 
} 
 
void CHomeResDlg::OnSysCommand(UINT nID, LPARAM lParam) 
{ 
	if ((nID & 0xFFF0) == IDM_ABOUTBOX) 
	{ 
		CAboutDlg dlgAbout; 
		dlgAbout.DoModal(); 
	} 
	else 
	{ 
		CDialog::OnSysCommand(nID, lParam); 
	} 
} 
 
// If you add a minimize button to your dialog, you will need the code below 
//  to draw the icon.  For MFC applications using the document/view model, 
//  this is automatically done for you by the framework. 
 
void CHomeResDlg::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(); 
	} 
} 
 
// The system calls this to obtain the cursor to display while the user drags 
//  the minimized window. 
HCURSOR CHomeResDlg::OnQueryDragIcon() 
{ 
	return (HCURSOR) m_hIcon; 
} 
 
void CHomeResDlg::OnBtnAdd()  
{ 
	UpdateData(); 
	_RecordsetPtr	m_pRecordset; 
	m_pRecordset.CreateInstance(__uuidof(Recordset)); 
	try 
	{ 
		m_pRecordset->Open("SELECT * FROM Budget",                // 查询DemoTable表中所有字段 
			m_pConnection.GetInterfacePtr(),	 // 获取库接库的IDispatch指针 
			adOpenDynamic, 
			adLockOptimistic, 
			adCmdText); 
	} 
	catch(_com_error *e) 
	{ 
		AfxMessageBox(e->ErrorMessage()); 
	}   
 
	CString strDate,strType,strHandler; 
	GetDlgItem(IDC_DATETIMEPICKER_DATE)->GetWindowText(strDate); 
	m_cobType.GetWindowText(strType); 
	m_cobHandle.GetWindowText(strHandler); 
	 
	//添加新记录 
	m_pRecordset->AddNew(); 
	m_pRecordset->PutCollect("DateA",_variant_t(strDate)); 
	m_pRecordset->PutCollect("Content",_variant_t(m_strContent)); 
	m_pRecordset->PutCollect("MoneyA", _variant_t(m_fMoney)); 
	m_pRecordset->PutCollect("Handler", _variant_t(strHandler)); 
	m_pRecordset->PutCollect("Type", _variant_t(strType)); 
	m_pRecordset->Update(); 
 
	m_pRecordset->Close(); 
	m_pRecordset = NULL; 
 
	CTime Today = CTime::GetCurrentTime(); 
	Load(Today.GetMonth(),Today.GetMonth() + 1); 
} 
 
void CHomeResDlg::OnClose()  
{ 
	if(m_pConnection->State) 
        m_pConnection->Close(); 
	m_pConnection= NULL;      
	CDialog::OnClose(); 
} 
 
void CHomeResDlg::Load(int nFrom,int nTo,int nYear) 
{ 
	m_Tree.DeleteAllItems(); 
 
	CString strValue; 
	CString strTody; 
	GetDlgItem(IDC_DATETIMEPICKER_DATE)->GetWindowText(strTody); 
	CString strSql; 
	_variant_t var; 
	_RecordsetPtr pMonthRes,pTodayRes; 
	pTodayRes.CreateInstance(__uuidof(Recordset)); 
	pMonthRes.CreateInstance(__uuidof(Recordset)); 
	try 
	{		 
		strSql.Format("SELECT DateA,Sum(MoneyA) as MoneySum FROM Budget group by DateA having year(DateA)=%d and month(DateA) between %d and %d" , 
			nYear,nFrom,nTo); 
		//rSql="SELECT DateA,Sum(MoneyA) as MoneySum FROM Budget group by DateA having DateA>=#2004-8-1# and DateA<=#2004-8-2#"; 
		pMonthRes->Open(_variant_t(strSql),                // 查询DemoTable表中所有字段 
		m_pConnection.GetInterfacePtr(),	 // 获取库接库的IDispatch指针 
			adOpenDynamic, 
			adLockOptimistic, 
			adCmdText); 
	} 
	catch(_com_error *e) 
	{ 
		AfxMessageBox(e->ErrorMessage()); 
	}   
	 
	int i = 0; 
	long lID = 0; 
	HTREEITEM hDay = NULL; 
	HTREEITEM hDayItem = NULL; 
	while(!pMonthRes->adoEOF) 
	{	 
		// 
		var = pMonthRes->GetCollect("DateA"); 
		if(var.vt != VT_NULL) 
			strValue = (LPCSTR)_bstr_t(var); 
		 
		double dMoneySum; 
		var = pMonthRes->GetCollect((long)1); 
		if(var.vt != VT_NULL) 
			dMoneySum = (double)var; 
		CString strDayLable; 
		strDayLable.Format("%s/¥%2.2f",strValue,dMoneySum); 
		 
		hDay = m_Tree.InsertItem(strDayLable); 
		int nYear,nMonth,nDay; 
		nYear = atoi(strtok(strValue.GetBuffer(strValue.GetLength()),"-")); 
		nMonth = atoi(strtok(NULL,"-")); 
		nDay = atoi(strtok(NULL,"-")); 
		strValue.ReleaseBuffer(); 
		strSql.Format("SELECT * FROM Budget where Year(DateA)=%d and Month(DateA)=%d and Day(DateA)=%d", 
			nYear,nMonth,nDay); 
		//strSql = "SELECT * FROM Budget where ID=15"; 
		pTodayRes->Open(_variant_t(strSql),                // 查询DemoTable表中所有字段 
						m_pConnection.GetInterfacePtr(),	 // 获取库接库的IDispatch指针 
						adOpenDynamic, 
						adLockOptimistic, 
						adCmdText); 
 
		while(!pTodayRes->adoEOF) 
		{ 
			// 
			var = pTodayRes->GetCollect("Content"); 
			if(var.vt != VT_NULL) 
				strValue = (LPCSTR)_bstr_t(var); 
			strValue += '/'; 
			 
			// 
			var = pTodayRes->GetCollect("Type"); 
			if(var.vt != VT_NULL) 
				strValue += (LPCSTR)_bstr_t(var); 
			strValue += "/¥"; 
			// 
			var = pTodayRes->GetCollect("MoneyA"); 
			if(var.vt != VT_NULL) 
				strValue += (LPCSTR)_bstr_t(var); 
			strValue += '/'; 
			// 
			var = pTodayRes->GetCollect("Handler"); 
			if(var.vt != VT_NULL) 
				strValue += (LPCSTR)_bstr_t(var); 
			 
			var = pTodayRes->GetCollect("ID"); 
			if(var.vt != VT_NULL) 
				lID = (long)var; 
			 
			hDayItem = m_Tree.InsertItem(strValue,hDay); 
			m_Tree.SetItemData(hDayItem,lID); 
			 
			pTodayRes->MoveNext(); 
		} 
		pTodayRes->Close(); 
		 
		pMonthRes->MoveNext(); 
		i++; 
	} 
 
	pMonthRes->Close(); 
	pMonthRes = NULL; 
 
	m_Tree.Expand(hDay,TVE_EXPAND); 
} 
 
void CHomeResDlg::OnBtnModify()  
{ 
	//Load(m_tDate.GetMonth(),m_tDate.GetMonth() + 1); 
	UpdateData(); 
	if(m_lCurID > 0) 
	{ 
		int nCurSel = 0; 
		int nID = 0; 
		CString strDate,strType,strHandler; 
		m_Date.GetWindowText(strDate); 
		m_cobType.GetWindowText(strType); 
		m_cobHandle.GetWindowText(strHandler); 
		CString strSql; 
		strSql.Format("update Budget set DateA='%s',Content='%s',MoneyA=%f,Handler='%s',Type='%s' where ID=%d", 
			strDate,m_strContent,m_fMoney,strHandler,strType,m_lCurID); 
		_variant_t vAffected; 
		m_pConnection->Execute(_bstr_t(strSql),&vAffected,adCmdText); 
		 
		CTime Today = CTime::GetCurrentTime(); 
		Load(Today.GetMonth(),Today.GetMonth() + 1); 
 
	} 
} 
 
 
void CHomeResDlg::OnBtnDel()  
{ 
	if(m_lCurID > 0 && AfxMessageBox("是否删除?",MB_YESNO) == IDYES) 
	{ 
		CString strSql; 
		strSql.Format("delete from Budget where ID=%d",m_lCurID); 
		_variant_t RecordsAffected; 
		m_pConnection->Execute(_bstr_t(strSql),&RecordsAffected,adCmdText); 
		CTime Today = CTime::GetCurrentTime(); 
		Load(Today.GetMonth(),Today.GetMonth() + 1); 
	} 
} 
 
void CHomeResDlg::OnBtnAna()  
{ 
	CString strAnaType,strAnaHandler,strDateFrom,strDateTo; 
	m_DateFrom.GetWindowText(strDateFrom); 
	m_DateTo.GetWindowText(strDateTo); 
	m_cobAnaType.GetWindowText(strAnaType); 
	m_cobAnaHandler.GetWindowText(strAnaHandler); 
	CString strSql,strTemp; 
	strSql.Format("select SUM(MoneyA) as SumMoneyA from Budget where DateA>=#%s# and DateA<=#%s#", 
		strDateFrom,strDateTo); 
	if(strAnaType != "全部类型") 
	{ 
		strTemp.Format(" and Type='%s'",strAnaType); 
		strSql += strTemp; 
	} 
	if(strAnaHandler != "全部人") 
	{ 
		strTemp.Format(" and Handler='%s'",strAnaHandler); 
		strSql += strTemp; 
	} 
 
	strTemp.Format("时间:%s-> %s",strDateFrom,strDateTo); 
	m_ResList.AddString(strTemp); 
	strTemp.Format("类型:%s",strAnaType); 
	m_ResList.AddString(strTemp); 
	strTemp.Format("经手人:%s",strAnaHandler); 
	m_ResList.AddString(strTemp); 
	 
	_RecordsetPtr SumRecordset; 
	_variant_t vSum; 
/* 
	SumRecordset.CreateInstance(__uuidof(Recordset)); 
	try 
	{ 
		SumRecordset->Open(_bstr_t(strSql),                // 查询DemoTable表中所有字段 
			m_pConnection.GetInterfacePtr(),	 // 获取库接库的IDispatch指针 
			adOpenDynamic, 
			adLockOptimistic, 
			adCmdText); 
	} 
	catch(_com_error *e) 
	{ 
		AfxMessageBox(e->ErrorMessage()); 
	}  */ 
 
	SumRecordset = m_pConnection->Execute(_bstr_t(strSql),&vSum,adCmdText); 
	while(!SumRecordset->adoEOF) 
	{ 
		vSum = SumRecordset->GetCollect("SumMoneyA"); 
		if(vSum.vt != VT_NULL) 
		{ 
			strTemp.Format("总计:¥%.2f元",(float)vSum); 
			m_ResList.AddString(strTemp); 
		} 
		else 
		{ 
			m_ResList.AddString("总计:¥0.00元"); 
		} 
		SumRecordset->MoveNext(); 
	} 
	SumRecordset->Close(); 
	m_ResList.AddString("----------------"); 
} 
 
void CHomeResDlg::OnSelchangedTreeBudget(NMHDR* pNMHDR, LRESULT* pResult)  
{ 
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; 
	HTREEITEM hCurItem = pNMTreeView->itemNew.hItem; 
	if(m_Tree.GetParentItem(hCurItem) != NULL) 
	{ 
		CString strDate = m_Tree.GetItemText(m_Tree.GetParentItem(hCurItem)); 
		int nPos = strDate.Find('/'); 
		strDate = strDate.Left(nPos); 
		m_CurTime.wYear = atoi(strtok(strDate.GetBuffer(strDate.GetLength()),"-")); 
		m_CurTime.wMonth = atoi(strtok(NULL,"-")); 
		m_CurTime.wDay = atoi(strtok(NULL,"-")); 
		m_Date.SetTime(m_CurTime); 
		strDate.ReleaseBuffer(); 
 
		CString strText = m_Tree.GetItemText(hCurItem); 
		m_lCurID = m_Tree.GetItemData(hCurItem); 
		m_strContent = strtok(strText.GetBuffer(strText.GetLength()),"/"); 
		m_nType = m_cobType.SelectString(-1,strtok(NULL,"/")); 
		CString strMoney = strtok(NULL,"/"); 
		strMoney = strMoney.Right(strMoney.GetLength() - 2); 
		m_fMoney = (float)atof(strMoney); 
		m_nHandler = m_cobHandle.SelectString(-1,strtok(NULL,"/")); 
		 
		strText.ReleaseBuffer(); 
		UpdateData(FALSE); 
	}	 
	else 
	{ 
		m_lCurID = 0; 
	} 
	*pResult = 0; 
}