⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 databasedlg.cpp

📁 对数据库简单的调用、添加、删除
💻 CPP
字号:
// DatabaseDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Database.h"
#include "DatabaseDlg.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()

/////////////////////////////////////////////////////////////////////////////
// CDatabaseDlg dialog

CDatabaseDlg::CDatabaseDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CDatabaseDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDatabaseDlg)
	id = _T("");
	name = _T("");
	birth = 0;
	sex = _T("");
	age = _T("");
	state = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CDatabaseDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDatabaseDlg)
	DDX_Control(pDX, IDC_INFOLIST, m_infolist);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CDatabaseDlg, CDialog)
	//{{AFX_MSG_MAP(CDatabaseDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_ADD, OnAdd)
	ON_BN_CLICKED(IDC_MODIFY, OnModify)
	ON_BN_CLICKED(IDC_REFURBISH, OnRefurbish)
	ON_BN_CLICKED(IDC_DELETE, OnDelete)
	ON_BN_CLICKED(IDC_QUERY, OnQuery)
	ON_NOTIFY(NM_DBLCLK, IDC_INFOLIST, OnDblclkInfolist)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDatabaseDlg message handlers

BOOL CDatabaseDlg::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
	
	// TODO: Add extra initialization here

	//添加listcontrol列头
    m_infolist.SetExtendedStyle(LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT | LVS_EX_HEADERDRAGDROP);
 
    m_infolist.InsertColumn(0,"工号",LVCFMT_CENTER,50);
    m_infolist.InsertColumn(1,"姓名",LVCFMT_CENTER,50);
    m_infolist.InsertColumn(2,"出生年月",LVCFMT_CENTER,100);
    m_infolist.InsertColumn(3,"性别",LVCFMT_CENTER,50);
    m_infolist.InsertColumn(4,"年龄",LVCFMT_CENTER,50);
  

	LoadData();

/*
	CString   str;   
    CTime   t   =   CTime::GetCurrentTime();   
    str.Format("%d-%d-%d",t.GetYear(),t.GetMonth(),t.GetDay());   
    
    CString   strTime;   
    CTime   tTime   =   CTime::GetCurrentTime();   
    strTime   =   tTime.Format("%Y-%m-%d   %H:%M:%S");
	------------------------------------------------------
	CString   strCString="2004-08-12   14:45:22";     
    COleVariant   vtime(strCString);   
    vtime.ChangeType(VT_DATE);   
    COleDateTime   time4=vtime;   
    SYSTEMTIME   systime;   
    VariantTimeToSystemTime(time4,   &systime);   
    CTime   tm(systime);     //CString=======>CTime
*/
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CDatabaseDlg::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 CDatabaseDlg::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 CDatabaseDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CDatabaseDlg::OnAdd() 
{
	// TODO: Add your control notification handler code here
	
    dlg.m_state="添加";
	dlg.m_id.Empty();
	dlg.m_name.Empty();
	dlg.m_sex.Empty();
	dlg.m_age.Empty();

	if (dlg.DoModal()==IDOK)
	{
		id = dlg.m_id;
	    name = dlg.m_name;
	    birth = dlg.m_birth;
	    sex = dlg.m_sex;
	    age = dlg.m_age;
	
	    CString ph;
	    CString y_date,m_date,d_date;
	    y_date=birth.Format("%Y");
	    m_date.Format("%d",birth.GetMonth());
	    d_date.Format("%d",birth.GetDay());
	    if (m_date.GetLength()==1)
		{
			m_date=CString("0")+m_date;
		}
	    if (d_date.GetLength()==1)
		{
			d_date=CString("0")+d_date;
		}
        ph=y_date+"-"+m_date+"-"+d_date;
    
	    // 定义变量
	    CString strSQL;
	    strSQL="insert into doctor(ID,Name,Birth,Sex,Age) values('"+id+"','"+name+"','"+ph+"','"+sex+"','"+age+"')";
	    if (!OpenRecordSet(m_pRecordset,strSQL))
		{
			AfxMessageBox("没成功打开数据表");
		    return;
		}
	}
    LoadData();

}

void CDatabaseDlg::OnModify() 
{
	// TODO: Add your control notification handler code here
	dlg.m_state="修改";

	// 寻找当前选中记录的位置
	POSITION pos = m_infolist.GetFirstSelectedItemPosition();
	// 获得当前记录的位置游标
	int iIndex = m_infolist.GetNextSelectedItem(pos);
	if (iIndex==-1)
	{
		return;
	}
	// 获得该项在数据库中的序号
	CString strID, strName;
	strID=m_infolist.GetItemText(iIndex,0);
	strName=m_infolist.GetItemText(iIndex,1);
	// 设置查询语句
	CString strSQL;
	strSQL.Format("select * from doctor where ID='%s'\
		           and Name='%s'",\
				   strID, strName);

	if (!OpenRecordSet(m_pRecordset,strSQL))
	{
		AfxMessageBox("没成功打开数据表");
		return;
	}
    if (!m_pRecordset->adoBOF)
	{
		m_pRecordset->MoveFirst();
    }

	
	dlg.m_id=(LPCTSTR)(_bstr_t)m_pRecordset->GetCollect("ID");
	dlg.m_name=(LPCTSTR)(_bstr_t)m_pRecordset->GetCollect("Name");
	dlg.m_sex=(LPCTSTR)(_bstr_t)m_pRecordset->GetCollect("Sex");
	dlg.m_age=(LPCTSTR)(_bstr_t)m_pRecordset->GetCollect("Age");

/*
		CString   strDate=(LPCTSTR)(_bstr_t)m_pRecordset->GetCollect("Birth");   
		MessageBox(strDate);
	    COleVariant   vtime(strDate);   
	    vtime.ChangeType(VT_DATE);   
	    COleDateTime   time4=vtime;   
		dlg.m_birth=time4;*/
	

	if (dlg.DoModal()==IDOK)
	{
		try
		{
			m_pRecordset->PutCollect("ID",_variant_t(dlg.m_id));
			m_pRecordset->PutCollect("Name",_variant_t(dlg.m_name));
			m_pRecordset->PutCollect("Sex",_variant_t(dlg.m_sex));
			m_pRecordset->PutCollect("Age",_variant_t(dlg.m_age));

/*			// 出生日期
			COleDateTime oleTime;
			CDateTimeCtrl *pDtCtrl=(CDateTimeCtrl*)dlg.GetDlgItem(IDC_DATEBIRTH);
			pDtCtrl->GetTime(oleTime);
			m_pRecordset->PutCollect("Birth",_variant_t(oleTime));
*/

			// 更新数据库
			m_pRecordset->Update();
//		    //当前记录移动到最后
// 			m_pRecordset->MoveLast();
		}
		catch (_com_error e)
		{
			CString strError;
			strError.Format("警告:打开数据表时发生异常。错误信息:%s", e.ErrorMessage());
		    AfxMessageBox(strError);
		}

	}
    LoadData();
}

void CDatabaseDlg::OnRefurbish() 
{
	// TODO: Add your control notification handler code here
	LoadData();
}

void CDatabaseDlg::OnDelete() 
{
	// TODO: Add your control notification handler code here
	//寻找当前选中的记录位置
	POSITION pos=m_infolist.GetFirstSelectedItemPosition();
	if(pos==NULL)
	{
		//如果没有选择记录,则提示并退出
		AfxMessageBox("请您选择要删除的信息");
		return;
	}
	int iIndex=m_infolist.GetNextSelectedItem(pos);
	//表
	CString strID,strName;
	strID=m_infolist.GetItemText(iIndex,0);
	strName=m_infolist.GetItemText(iIndex,1);
	//确认信息
	CString strHint;
	strHint.Format("是否删除:%s的个人信息?",strName);
	if(MessageBox(strHint,"删除确认",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		return;
	}
	//首先从列表中删除
	m_infolist.DeleteItem(iIndex);
	CString strSQL;
	strSQL.Format("select * from doctor where ID='%s' and Name='%s'",strID, strName);
	if(!OpenRecordSet(m_pRecordset,strSQL))
	{
		AfxMessageBox("基本信息没有成功打开");
		return;
	}
	//其次从数据库中删除
	m_pRecordset->Delete(adAffectCurrent);
//	m_pRecordset->Close();
//	m_pRecordset=NULL;
}

void CDatabaseDlg::OnQuery() 
{
	// TODO: Add your control notification handler code here
	
}

BOOL CDatabaseDlg::OpenRecordSet(_RecordsetPtr &recPtr, CString &strSQL)
{
	CDatabaseApp *pApp = (CDatabaseApp*)AfxGetApp();
	// 创建对象
	m_pRecordset.CreateInstance("ADODB.Recordset");
	
	try
	{
		// 从数据库中打开表
		recPtr->Open(strSQL.AllocSysString(),
			         pApp->m_pConnection.GetInterfacePtr(),
					 adOpenDynamic,
					 adLockOptimistic,
					 adCmdText);
	}
	catch (_com_error e)
	{
		CString strError;
		strError.Format("警告:打开数据表时发生异常。错误信息:%s", e.ErrorMessage());
		AfxMessageBox(strError);

		return FALSE;
	}
    
	return TRUE;
}


void CDatabaseDlg::LoadData()
{
	// 定义变量
	CString strSQL;
	// 打开记录集,选择表名
	strSQL = "select * from doctor ";
	if (!OpenRecordSet(m_pRecordset,strSQL))
	{
		AfxMessageBox("没成功打开数据表");
		return;
	}

	m_infolist.DeleteAllItems();
	int i=0;
	while(!m_pRecordset->adoEOF)
	{
		m_infolist.InsertItem(i,(LPCTSTR)(_bstr_t)m_pRecordset->GetCollect("ID"));
        m_infolist.SetItemText(i,1,(LPCTSTR)(_bstr_t)m_pRecordset->GetCollect("Name"));
        m_infolist.SetItemText(i,2,(LPCTSTR)(_bstr_t)m_pRecordset->GetCollect("Birth"));
        m_infolist.SetItemText(i,3,(LPCTSTR)(_bstr_t)m_pRecordset->GetCollect("Sex"));
		m_infolist.SetItemText(i,4,(LPCTSTR)(_bstr_t)m_pRecordset->GetCollect("Age"));
        i++;
        m_pRecordset->MoveNext();
	}

}

void CDatabaseDlg::OnDblclkInfolist(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	OnModify();
	*pResult = 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -