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

📄 dbdemodlg.cpp

📁 VC++与ACCESS数据库操作例程。创建数据库
💻 CPP
字号:
// DBDemoDlg.cpp : implementation file
//

#include "stdafx.h"
#include "DBDemo.h"
#include "DBDemoDlg.h"

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

extern CString fileDBName;
extern CString fileDBTitle;
extern CDBDemoApp theApp;

/////////////////////////////////////////////////////////////////////////////
// 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()

/////////////////////////////////////////////////////////////////////////////
// CDBDemoDlg dialog

CDBDemoDlg::CDBDemoDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CDBDemoDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDBDemoDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CDBDemoDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDBDemoDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CDBDemoDlg, CDialog)
	//{{AFX_MSG_MAP(CDBDemoDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_DB_CONNECT, OnButtonDbConnect)
	ON_BN_CLICKED(IDC_BUTTON3, OnButton3)
	ON_BN_CLICKED(IDC_BUTTON_DB_CLOSE, OnButtonDbClose)
	ON_BN_CLICKED(IDC_QUERY, OnQuery)
	ON_BN_CLICKED(IDC_BUTTON_INSERT, OnButtonInsert)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDBDemoDlg message handlers

BOOL CDBDemoDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	AfxOleInit();
	CoInitialize(NULL);   

	// 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
	CRect rect;
	GetClientRect(&rect);
	CRect rectQuery;
	CRect rectLeft;

	GetDlgItem(IDC_QUERY)->GetWindowRect(&rectQuery);
	GetDlgItem(IDC_BUTTON_DB_CONNECT)->GetWindowRect(&rectLeft);
	ScreenToClient(&rectQuery);
	ScreenToClient(&rectLeft);
	rect.left=rectLeft.right+10;
	rect.top+=10;
	rect.right-=10;
	rect.bottom=rectQuery.top-10;
	BOOL bl=m_ListCtrl.Create(WS_BORDER|WS_VISIBLE|LVS_REPORT,rect,this,IDC_LIST_DB);
	m_ListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT);
	m_ListCtrl.InsertColumn(0,"学号",LVCFMT_LEFT,50);	
	m_ListCtrl.InsertColumn(1,"姓名",LVCFMT_LEFT,50);
	int n=m_ListCtrl.InsertItem(0,"1");
	m_ListCtrl.SetItemText(n,1,"张三");
	n=m_ListCtrl.InsertItem(1,"2");
	m_ListCtrl.SetItemText(n,1,"李四");		
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

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

void CDBDemoDlg::OnOK() 
{	// TODO: Add extra validation here

	CDialog::OnOK();
}

void CDBDemoDlg::OnButtonDbConnect() 
{
	// TODO: Add your control notification handler code here
	CFileDialog dlg(TRUE,_T("*.mdb"),NULL,OFN_PATHMUSTEXIST
		                                  |OFN_OVERWRITEPROMPT
										  |OFN_HIDEREADONLY,
					_T("*.mdb|*.mdb||"),this);                
	if(dlg.DoModal()!=IDOK)
		return;	
	fileDBName=dlg.GetPathName();
	CString strConn;
	strConn=_T("Provider=Microsoft.JET.OLEDB.4.0;Data Source=");
	strConn+=fileDBName;
	try
	{
		HRESULT hr=m_pConnection.CreateInstance("ADODB.Connection") ;
		if(SUCCEEDED(hr))
		{
			hr=m_pConnection->Open((LPCTSTR)strConn,"","",adModeUnknown);
		}
	}
	catch(_com_error e)
	{
		CString errorMessage;
		errorMessage.Format("连接数据库失败!\r\n 错误信息:%s",e.ErrorMessage());
		AfxMessageBox(errorMessage);
		
	}
	if(m_pConnection->State)
		AfxMessageBox("已经正确连接数据库");

	
}

void CDBDemoDlg::OnButton3() 
{
	// TODO: Add your control notification handler code here
	CFileDialog dlg(FALSE,_T("*.mdb"),NULL,OFN_PATHMUSTEXIST
		                                  |OFN_OVERWRITEPROMPT
										  |OFN_HIDEREADONLY,
					_T("*.mdb|*.mdb||"),this);                
	if(dlg.DoModal()!=IDOK)
		return;
	
	fileDBName=dlg.GetPathName();
	fileDBTitle=dlg.GetFileName();
	CString strConn;
	strConn=_T("Provider=Microsoft.JET.OLEDB.4.0;Data Source=");
	strConn+=fileDBName;
	CString strSql=_T("CREATE TABLE Students(StudentID Char(7) not null,");
	strSql+=_T("StudentName nVarchar(32) not null)");
	try
	{
		{		
			ADOX::_CatalogPtr pCatalog=NULL;		
			HRESULT hr=pCatalog.CreateInstance(__uuidof(ADOX::Catalog));		
			if(FAILED(hr))		
			{			
				AfxMessageBox(_T("创建失败"));			
				return;		
			}		
			pCatalog->Create(_bstr_t(strConn));
		}
		_ConnectionPtr pConnection=NULL;
		pConnection.CreateInstance(__uuidof(Connection));
		pConnection->Open((LPCTSTR)strConn,"","",adModeUnknown);
		_variant_t ra;
		pConnection->Execute((LPCTSTR)strSql,&ra,adCmdText);
		pConnection->Close();
		AfxMessageBox(_T("创建库及表成功"));
	}
	catch(_com_error &ex)
	{
		AfxMessageBox(ex.Description());
	}	
	
}

void CDBDemoDlg::OnCancel() 
{
	// TODO: Add extra cleanup here
	
	CDialog::OnCancel();
}

void CDBDemoDlg::OnButtonDbClose() 
{
	// TODO: Add your control notification handler code here
	if(m_pConnection->State)		
	{
		m_pConnection->Close();
		AfxMessageBox("数据库关闭成功");
	}
	else 
		AfxMessageBox("数据库已经关闭");
	
}

void CDBDemoDlg::OnQuery() 
{
	// TODO: Add your control notification handler code here
	CString strSQL="";
	int nFieldsCount=0;
	long i=0;
	CString strFieldName="";
	m_pRecordset.CreateInstance("ADODB.Recordset");//创建Recordset实例
	strSQL="SELECT studentID,studentName FROM students ";
	try
	{
		m_pRecordset->Open((_variant_t)strSQL,(IDispatch*)m_pConnection,
			adOpenDynamic,adLockOptimistic,adCmdText);//打开记录集	
	}
	catch (_com_error* e)
	{
		AfxMessageBox(e->ErrorMessage());//弹出错误对话框
	}
	
	try
	{
		nFieldsCount=m_pRecordset->GetFields()->Count;//得到字段数
	}
	catch (_com_error* e)
	{
		AfxMessageBox(e->ErrorMessage());//弹出错误对话框
	}

	//清空列表控件
	int nListColCount=0;
	nListColCount=m_ListCtrl.GetHeaderCtrl()->GetItemCount();
	m_ListCtrl.DeleteAllItems();
	for (i=nListColCount-1;i>=0;i--)
	{
		m_ListCtrl.DeleteColumn(i);
	}	

	//添加新的字段,字段名为读取表中的各字段名
	/*
	for (i=0;i<nFieldsCount;i++)
	{
		strFieldName=LPCTSTR(m_pRecordset->GetFields()->GetItem(_variant_t(i))->Name);
		m_ListCtrl.InsertColumn(i,strFieldName,LVCFMT_LEFT,50,50);
	}
	*/
	//for (i=0;i<nFieldsCount;i++)
	//{
		//strFieldName=LPCTSTR(m_pRecordset->GetFields()->GetItem(_variant_t(i))->Name);
		m_ListCtrl.InsertColumn(0,"学生编号",LVCFMT_LEFT,50,50);
		m_ListCtrl.InsertColumn(1,"学生姓名",LVCFMT_LEFT,50,50);
	//}

	_variant_t var;
	CString strItemValue;//当前记录当前字段的值
	int nItem=0;//当前插入记录的行数
	long nFirstCol=0;//第一列的索引,为0
	int nIndex=0;//标记当前记录索引,从0开始

	while (!m_pRecordset->adoEOF)
	{
		//得到当前记录第一个字段的值
		var=m_pRecordset->GetCollect(_variant_t(nFirstCol));
		if (var.vt!=VT_NULL)
		{
			//类型转换,将_variant_t转换为CString
			strItemValue=LPCTSTR(_bstr_t(var));
		}
		//插入记录并填入第一个字段的值
		nItem=m_ListCtrl.InsertItem(nIndex,strItemValue);
		//循环一下,读取数据库中当前记录的值并填入列表控件
		for (i=1;i<nFieldsCount;i++)
		{
			var=m_pRecordset->GetCollect(_variant_t(i));
			if (var.vt!=VT_NULL)
			{
				strItemValue=LPCTSTR(_bstr_t(var));
				m_ListCtrl.SetItemText(nItem,i,strItemValue);
			}
		}
		m_pRecordset->MoveNext();//转入数据库下一记录
		nIndex++;//当前记录索引加1
	}

	//防止闪烁
	m_ListCtrl.ShowWindow(SW_HIDE);
	for (i=0;i<nFieldsCount;i++)
	{
		//自动调整列宽
		m_ListCtrl.SetColumnWidth(i,LVSCW_AUTOSIZE_USEHEADER);
	}
	m_ListCtrl.ShowWindow(SW_SHOW);	
	
}

void CDBDemoDlg::OnButtonInsert() 
{
	// TODO: Add your control notification handler code here
	CString strSQL="";
	int nFieldsCount=0;
	long i=0;
	CString strFieldName="";
	m_pRecordset.CreateInstance("ADODB.Recordset");//创建Recordset实例
	strSQL="SELECT studentID,studentName FROM students ";
	try
	{
		m_pRecordset->Open((_variant_t)strSQL,(IDispatch*)m_pConnection,
			adOpenDynamic,adLockOptimistic,adCmdText);//打开记录集	
		m_pRecordset->AddNew();
		m_pRecordset->PutCollect("StudentID", "1222");
		m_pRecordset->PutCollect("StudentName", "老贵");
		m_pRecordset->Update();
	}
	catch (_com_error* e)
	{
		AfxMessageBox(e->ErrorMessage());//弹出错误对话框
	}
	
	
}

⌨️ 快捷键说明

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