MFC学习记录3之Mini系统2
1.为系统增加按钮,此次先增加一个删除按钮:
并为连接对象增加销毁函数,代码如下
销毁函数如下:
void CMiniMsDlg::OnDestroy()
{
CDialogEx::OnDestroy();
// TODO: 在此处添加消息处理程序代码
if(m_pConnection!=NULL)
if(m_pConnection->State)
m_pConnection->Close();
}
然后增加为删除按钮增加事件,代码如下:
void CMiniMsDlg::OnBnClickedButtonDelete()
{
// TODO: 在此添加控件通知处理程序代码
int nIndex=m_list.GetSelectionMark();
if(nIndex<0){
return;
}
int nID=m_list.GetItemData(nIndex);
TCHAR szSql[1024]={0};
_stprintf(szSql,_T("delete from Students where StudentId=%d"),nID);
Execute(szSql);
GetDataset();
}
其中Execute(szSql)和GetDataset()函数就是将函数进行一个封装,以用来实现系统的模块化管理:
这两个函数声明都是在头文件MiniMsDlg.h中:
void GetDataset();
void Execute(LPCTSTR lpSql);
然后具体的实现Execute(szSql):
void CMiniMsDlg::Execute(LPCTSTR lpSql){
_variant_t ra;
try{
m_pConnection->Execute(lpSql,&ra,adCmdText);
}catch(_com_error &e){
AfxMessageBox((LPCTSTR)e.Description());
}
catch(...){
AfxMessageBox(_T("执行发生未知错误!"));
}
}
GetDataset()其实就是重新读取一下数据库中的数据,具体函数实现如下:
void CMiniMsDlg::GetDataset(){
LPCTSTR lpSql=_T("select * from Students order by StudentID");
m_pRecordset->Open((_variant_t)lpSql,m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
if(m_pRecordset==NULL){
AfxMessageBox(_T("读取数据库失败"));
return;
}
m_list.DeleteAllItems();
int nitem=0;
_variant_t id,name;
CString strId,strName;
while(!m_pRecordset->adoEOF){
id=m_pRecordset->GetCollect(_T("StudentId"));
name=m_pRecordset->GetCollect(_T("StudentName"));
strId.Format(_T("%d"),id.intVal);
strName=(LPCTSTR)_bstr_t(name);
//AfxMessageBox(_T("11111"));
m_list.InsertItem(nitem,strId);
m_list.SetItemText(nitem,1,strName);
m_list.SetItemData(nitem,id.intVal);
nitem++;
m_pRecordset->MoveNext();
}
m_pRecordset->Close();
}