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

📄 connectdbdlg.cpp

📁 ADO通讯录管理,是一个VC+access 通过ADO连接,操作数据库.
💻 CPP
字号:
// connectDBDlg.cpp : implementation file
//

#include "stdafx.h"
#include "connectDB.h"
#include "connectDBDlg.h"
#include <comdef.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

extern CConnectDBApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CConnectDBDlg dialog

CConnectDBDlg::CConnectDBDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CConnectDBDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CConnectDBDlg)
	m_name = _T("");
	m_addr = _T("");
	m_tel = _T("");
	m_sex = _T("");
	m_bSuccess = FALSE;
	type=0;
	currentID="";
	mof_flag=0;

	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CConnectDBDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CConnectDBDlg)
	DDX_Control(pDX, IDC_PIC, m_pic);
	DDX_Control(pDX, IDC_LIST1, m_userlist);
	DDX_Text(pDX, IDC_NAME_EDT, m_name);
	DDX_Text(pDX, IDC_ADDR_EDT, m_addr);
	DDX_Text(pDX, IDC_TEL_EDT, m_tel);
	DDX_CBString(pDX, IDC_SEX_COMB, m_sex);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CConnectDBDlg, CDialog)
	//{{AFX_MSG_MAP(CConnectDBDlg)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_ADD_BTN, OnAddBtn)
	ON_BN_CLICKED(IDC_SAVE_BTN, OnSaveBtn)
	ON_NOTIFY(NM_DBLCLK, IDC_LIST1, OnDblclkList1)
	ON_NOTIFY(NM_CLICK, IDC_LIST1, OnClickList1)
	ON_BN_CLICKED(IDC_DELETE_BTN, OnDeleteBtn)
	ON_BN_CLICKED(IDC_MOTIFY_BTN, OnMotifyBtn)
	ON_BN_CLICKED(IDC_PIC, OnPic)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CConnectDBDlg message handlers

BOOL CConnectDBDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// 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
//------------------------------------------------------------------
	LONG lStyle = m_userlist.SendMessage
	(LVM_GETEXTENDEDLISTVIEWSTYLE);
	lStyle |= LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_HEADERDRAGDROP;
	m_userlist.SendMessage(LVM_SETEXTENDEDLISTVIEWSTYLE, 0,(LPARAM)lStyle);
	LV_COLUMN lvc;
	lvc.mask = LVCF_TEXT | LVCF_SUBITEM | LVCF_WIDTH ;//| LVCF_FMT;	

	m_userlist.InsertColumn(0,"用户ID",LVCFMT_LEFT,40);
	m_userlist.InsertColumn(1,"用户名",LVCFMT_LEFT,100);
	m_userlist.InsertColumn(2,"性别",LVCFMT_LEFT,30);
	m_userlist.InsertColumn(3,"电话",LVCFMT_LEFT,90);
	m_userlist.InsertColumn(4,"地址",LVCFMT_LEFT,130);
	showLists();
//=-----------------------------------------------------------
	GetDlgItem(IDC_NAME_EDT)->EnableWindow(FALSE);
	GetDlgItem(IDC_TEL_EDT)->EnableWindow(FALSE);
	GetDlgItem(IDC_ADDR_EDT)->EnableWindow(FALSE);
	GetDlgItem(IDC_SEX_COMB)->EnableWindow(FALSE);
	GetDlgItem(IDC_SAVE_BTN)->EnableWindow(FALSE);
	GetDlgItem(IDC_MOTIFY_BTN)->EnableWindow(FALSE);
	GetDlgItem(IDC_DELETE_BTN)->EnableWindow(FALSE);

	//-----------------------------------------------------------------
	CRect picRect,wndRect;
	GetWindowRect(&wndRect);
	GetDlgItem(IDC_PIC)->GetWindowRect(&picRect);
//		GetDlgItem(IDC_DISPLAY_AREA)->GetWindowRect(&AreaRect);
	ScreenToClient(&picRect);

	showRect=CRect(picRect.left+2,picRect.top+2,picRect.right-2,picRect.bottom-2);
	CClientDC dc(this);
	m_Pic.ShowBitmapResource(&dc,IDB_BITMAP1,showRect);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

// 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 CConnectDBDlg::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);
//		m_Pic.UpdateSizeOnDC(&dc); // Get Picture Dimentions In Pixels
//		m_Pic.Show(&dc,showRect);


	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CConnectDBDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CConnectDBDlg::OnAddBtn() 
{
	SetDlgItemText(IDC_NAME_EDT,"");
	SetDlgItemText(IDC_TEL_EDT,"");
	SetDlgItemText(IDC_ADDR_EDT,"");
	SetDlgItemText(IDC_SEX_COMB,"");
	GetDlgItem(IDC_NAME_EDT)->EnableWindow(TRUE);
	GetDlgItem(IDC_TEL_EDT)->EnableWindow(TRUE);
	GetDlgItem(IDC_ADDR_EDT)->EnableWindow(TRUE);
	GetDlgItem(IDC_SEX_COMB)->EnableWindow(TRUE);
	GetDlgItem(IDC_SAVE_BTN)->EnableWindow(TRUE);
	GetDlgItem(IDC_MOTIFY_BTN)->EnableWindow(FALSE);
	GetDlgItem(IDC_ADD_BTN)->EnableWindow(FALSE);
	type=1;
}

void CConnectDBDlg::OnCancel() 
{
	CDialog::OnCancel();
}

void CConnectDBDlg::OnSaveBtn() 
{
//	UpdateData(TRUE);
	if(!checkInput())return;
	if(type==1)
	{
		m_pRecordset.CreateInstance("ADODB.Recordset");
		m_pRecordset->Open("SELECT * FROM data1",_variant_t((IDispatch*)theApp.m_pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);
		try
		{
			// 写入各字段值
			m_pRecordset->AddNew();
			m_pRecordset->PutCollect("Name", _variant_t(m_name));
			m_pRecordset->PutCollect("sex", _variant_t(m_sex));
			m_pRecordset->PutCollect("tel", _variant_t(m_tel));
			m_pRecordset->PutCollect("addr", _variant_t(m_addr));
			m_pRecordset->GetFields()->GetItem("picture")->AppendChunk(varBLOB);
			m_pRecordset->Update();

			AfxMessageBox("添加成功!");
		}
		catch(_com_error *e)
		{
			AfxMessageBox(e->ErrorMessage());
		}
//	m_pRecordset->Close();
	}
	if(type==2)
	{
		CString sql="SELECT * FROM data1 where id=";
		sql+=currentID;
		m_pRecordset.CreateInstance("ADODB.Recordset");
		m_pRecordset->Open(_bstr_t(sql),_variant_t((IDispatch*)theApp.m_pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);
		if(m_pRecordset->BOF&&m_pRecordset->adoEOF)
		{
			AfxMessageBox("修改失败!");
		}
		else
		{
			m_pRecordset->PutCollect("name",_variant_t(m_name));
			m_pRecordset->PutCollect("sex",_variant_t(m_sex));
			m_pRecordset->PutCollect("tel",_variant_t(m_tel));
			m_pRecordset->PutCollect("addr",_variant_t(m_addr));
			if(mof_flag==2)
				m_pRecordset->GetFields()->GetItem("picture")->AppendChunk(varBLOB);
			m_pRecordset->Update();
			mof_flag=0;
			AfxMessageBox("修改成功!");

		}
	}
	showLists();
	GetDlgItem(IDC_NAME_EDT)->EnableWindow(FALSE);
	GetDlgItem(IDC_TEL_EDT)->EnableWindow(FALSE);
	GetDlgItem(IDC_ADDR_EDT)->EnableWindow(FALSE);
	GetDlgItem(IDC_ADD_BTN)->EnableWindow(TRUE);
	GetDlgItem(IDC_SEX_COMB)->EnableWindow(FALSE);
	GetDlgItem(IDC_SAVE_BTN)->EnableWindow(FALSE);
}
//-------------------------------------显示所有记录--------------------------------
void CConnectDBDlg::showLists()
{
	m_userlist.DeleteAllItems();
	int nItem;
	_variant_t vname,vsex,vid,vtel,vaddr;
	try
	{
		m_pRecordset.CreateInstance("ADODB.Recordset");
		m_pRecordset->Open("SELECT * FROM data1",_variant_t((IDispatch*)theApp.m_pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);
		m_bSuccess = TRUE;
		while(!m_pRecordset->adoEOF)
		{
			vid = m_pRecordset->GetCollect("id");
			vname = m_pRecordset->GetCollect("name");
			vsex= m_pRecordset->GetCollect("sex");
			vtel = m_pRecordset->GetCollect("tel");
			vaddr = m_pRecordset->GetCollect("addr");
			nItem=m_userlist.InsertItem(0xffff,(_bstr_t)vid);
			m_userlist.SetItem(nItem,1,1,(_bstr_t)vname,NULL,0,0,0);
			m_userlist.SetItem(nItem,2,1,(_bstr_t)vsex,NULL,0,0,0);
			m_userlist.SetItem(nItem,3,1,(_bstr_t)vtel,NULL,0,0,0);
			m_userlist.SetItem(nItem,4,1,(_bstr_t)vaddr,NULL,0,0,0);
			m_pRecordset->MoveNext();
		}
	}
	catch(_com_error e)///捕捉异常
	{
		AfxMessageBox("读取数据库失败!");///显示错误信息
	}
//	m_pRecordset->Close();

}

void CConnectDBDlg::OnDblclkList1(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
//	CString tname,tsex,ttel,taddr;
	*pResult = 0;
}

void CConnectDBDlg::OnClickList1(NMHDR* pNMHDR, LRESULT* pResult) 
{
	GetDlgItem(IDC_MOTIFY_BTN)->EnableWindow(TRUE);
	GetDlgItem(IDC_DELETE_BTN)->EnableWindow(TRUE);
	GetDlgItem(IDC_NAME_EDT)->EnableWindow(FALSE);
	GetDlgItem(IDC_TEL_EDT)->EnableWindow(FALSE);
	GetDlgItem(IDC_ADDR_EDT)->EnableWindow(FALSE);
	GetDlgItem(IDC_SEX_COMB)->EnableWindow(FALSE);
	GetDlgItem(IDC_SAVE_BTN)->EnableWindow(FALSE);
	GetDlgItem(IDC_ADD_BTN)->EnableWindow(TRUE);
	type=0;

	CListCtrl* pListCtrl = (CListCtrl*) GetDlgItem(IDC_LIST1);
	ASSERT(pListCtrl != NULL);
	POSITION pos = pListCtrl->GetFirstSelectedItemPosition();//得到当前选择位置
	if (pos == NULL)   
		TRACE0("No items were selected!\n");
	else{   
			while (pos)   
			{      
				int nItem = pListCtrl->GetNextSelectedItem(pos);
				currentID=pListCtrl->GetItemText(nItem,0);//得到当前用户ID
				SetDlgItemText(IDC_NAME_EDT,pListCtrl->GetItemText(nItem,1));	  
				SetDlgItemText(IDC_SEX_COMB,pListCtrl->GetItemText(nItem,2));	  
				SetDlgItemText(IDC_TEL_EDT,pListCtrl->GetItemText(nItem,3));	  
				SetDlgItemText(IDC_ADDR_EDT,pListCtrl->GetItemText(nItem,4));
			} 
//----------------------------------------------------------------------
			CString sql;
			sql="SELECT * FROM data1 where id="+currentID;//SQL语句
			m_pRecordset.CreateInstance("ADODB.Recordset");//建立记录集对象
			m_pRecordset->Open(_bstr_t(sql),_variant_t((IDispatch*)theApp.m_pConnection,true),adOpenStatic,adLockOptimistic,adCmdText);
			long nSize = m_pRecordset->GetFields()->GetItem("picture")->ActualSize;//取出指定字段数据大小
			CClientDC dc(this);
			if(nSize > 0)//图片数据>0
			{
				_variant_t	BLOB;
				BLOB = m_pRecordset->GetFields()->GetItem("picture")->GetChunk(nSize);//取出指定字段数据
				if(BLOB.vt == (VT_ARRAY | VT_UI1))
				{
					if(BYTE *pBuffer = new BYTE [nSize+1])		///重新申请必要的存储空间
					{	
						char *pBuf = NULL;
						SafeArrayAccessData(BLOB.parray,(void **)&pBuf);
						memcpy(pBuffer,pBuf,nSize);				///复制数据到缓冲区pBuffer
						SafeArrayUnaccessData (BLOB.parray);
						(m_Pic.LoadPictureData(pBuffer, nSize));
						 delete [] pBuffer;
						 pBuf=0;
						 ///生成BITMAP对象
						 m_Pic.UpdateSizeOnDC(&dc); // Get Picture Dimentions In Pixels
						 m_Pic.Show(&dc,showRect);
						 varBLOB.vt=BLOB.vt;
						 varBLOB.parray=BLOB.parray;
					     mof_flag=1;
					}
				}
			}
			else// 没有存图片
			{
				m_Pic.ShowBitmapResource(&dc,IDB_BITMAP1, showRect);
			}
		}	
	*pResult = 0;
}
//---------------------------删除当前记录----------------
void CConnectDBDlg::OnDeleteBtn() 
{
	CString sql;
	_variant_t RecordsAffected;
	HRESULT hr;
	if(IDNO==MessageBox("你真的要删除当前记录吗?(Y/N)","提示",MB_YESNO))return;
	sql="delete FROM data1 where id="+currentID;
	try
	{
		m_pRecordset.CreateInstance("ADODB.Recordset");
		hr=theApp.m_pConnection->Execute(_bstr_t(sql),&RecordsAffected,adCmdText);
		if(SUCCEEDED(hr))
		{
			AfxMessageBox("删除成功!");///显示错误信息
			OnPaint();
		}
	}
	catch(_com_error e)///捕捉异常
	{
		AfxMessageBox("删除失败!");///显示错误信息
	}
//	m_pRecordset->Close();
	showLists();
}
//-------------------------------------设置为修改状态--------------------
void CConnectDBDlg::OnMotifyBtn() 
{
	GetDlgItem(IDC_NAME_EDT)->EnableWindow(TRUE);
	GetDlgItem(IDC_TEL_EDT)->EnableWindow(TRUE);
	GetDlgItem(IDC_ADDR_EDT)->EnableWindow(TRUE);
	GetDlgItem(IDC_SEX_COMB)->EnableWindow(TRUE);
	GetDlgItem(IDC_SAVE_BTN)->EnableWindow(TRUE);
	GetDlgItem(IDC_MOTIFY_BTN)->EnableWindow(FALSE);
	GetDlgItem(IDC_ADD_BTN)->EnableWindow(FALSE);
	type=2;
}
//-----------------------------------------选择图片----------------
void CConnectDBDlg::OnPic() 
{
	if(type!=0)
	{
	  CFile f;
	  CString  FilePathName;
	  CFileException e;

      CFileDialog dlg(TRUE,NULL,NULL,0,"jpg Files (*.jpg)|*.jpg|file(*.bmp)|*.bmp|file(*.gif)|*.gif||",this);///TRUE为OPEN对话框,FALSE为SAVE AS对话框
      if(dlg.DoModal()==IDOK)
      {
		FilePathName=dlg.GetPathName();
		if(m_Pic.m_IPicture != NULL) m_Pic.FreePictureData(); // Important - Avoid Leaks...

		if(f.Open(FilePathName, CFile::modeRead | CFile::typeBinary, &e)) //打开了一个jpg文件
		{	
			int nSize = f.GetLength();          //先得到jpg文件长度
		//	if( nSize >1024){MessageBox("请选择小于1M的图片!");return;}
			BYTE * pBuffer = new BYTE [nSize];  //按文件的大小在堆上申请一块内存

			if (f.Read(pBuffer, nSize) > 0 )    //把jpg文件读到pBuffer(堆上申请一块内存)
			{   // +----------------------------------------------
				BYTE *pBuf = pBuffer;     ///下面这一大段是把pBuffer里的jpg数据放到库中
				SAFEARRAY		*psa;
				SAFEARRAYBOUND	rgsabound[1];
				if(pBuf)
					{    
						rgsabound[0].lLbound = 0;
						rgsabound[0].cElements = nSize;
						psa = SafeArrayCreate(VT_UI1, 1, rgsabound);
						for (long i = 0; i < (long)nSize; i++)
						SafeArrayPutElement (psa, &i, pBuf++);
						varBLOB.vt = VT_ARRAY | VT_UI1;
						varBLOB.parray = psa;
						mof_flag=2;
					}
				(m_Pic.LoadPictureData(pBuffer, nSize));//接作调用函数读pBuffer的jpg数据准备显示
				delete [] pBuffer;     //删掉堆上申请的那一块内存
				pBuf=0;                //以防二次乱用
			}
			f.Close();
			CClientDC dc(this);        
			m_Pic.UpdateSizeOnDC(&dc); // Get Picture Dimentions In Pixels
			m_Pic.Show(&dc,showRect);//显示出来看看
		}
	  }
	}
}

BOOL CConnectDBDlg::checkInput()
{
	UpdateData(TRUE);
	if(!m_name||!m_sex||!m_tel||!m_addr||mof_flag==0)
	{
		MessageBox("请填写所有项内容!");
		return FALSE;
	}
	return TRUE;
}

⌨️ 快捷键说明

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