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

📄 adodlg.cpp

📁 实现ADO连接SQL SERVER 2000数据库
💻 CPP
字号:
// ADODlg.cpp : implementation file
//

#include "stdafx.h"
#include "ADO.h"
#include "ADODlg.h"

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

extern CADOApp theApp;
extern CString tmp;
char strOpen[100];
char kk[1024] ="";
char *g_totle;
CString mm;//记录要更新的行的第一个键值
int sum1;
/////////////////////////////////////////////////////////////////////////////
// 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()

/////////////////////////////////////////////////////////////////////////////
// CADODlg dialog

CADODlg::CADODlg(CWnd* pParent /*=NULL*/)
	: CDialog(CADODlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CADODlg)
		// 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 CADODlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CADODlg)
	DDX_Control(pDX, IDC_LIST1, m_list);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CADODlg, CDialog)
	//{{AFX_MSG_MAP(CADODlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_NOTIFY(NM_RCLICK, IDC_LIST1, OnRclickList1)
	ON_COMMAND(ID_ADD, OnAdd)
	ON_COMMAND(ID_MODIFY, OnModify)
	ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
	ON_COMMAND(ID_SELECT, OnSelect)
	ON_BN_CLICKED(IDC_BUTTON3, OnButton3)
	ON_COMMAND(ID_DELETE, OnDelete)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CADODlg message handlers

BOOL CADODlg::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
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

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

void CADODlg::OnRclickList1(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	CMenu menu; 
	CPoint pt;
	GetCursorPos(&pt);//取得鼠标位置 
	menu.LoadMenu(IDR_POPUP); 
	CMenu *pMenu = menu.GetSubMenu(0); 
	pMenu->TrackPopupMenu (0,pt.x,pt.y, this);
	
	*pResult = 0;
}

void CADODlg::OnAdd() 
{
	CEditIP dlg;

	dlg.nFlag = 1;
	
	dlg.DoModal();

	m_list.UpdateData(TRUE);
	UpdateList();
}

void CADODlg::OnModify() 
{
	CEditIP dlg;
	if( m_list.GetSelectedCount() > 0)
	{
		dlg.nFlag = 2;
		POSITION pos = m_list.GetFirstSelectedItemPosition();
		int nSelected = m_list.GetNextSelectedItem(pos);
		mm = m_list.GetItemText(nSelected, 0);
	}
	else
	{
		AfxMessageBox("若要修改记录,必须在记录的学号处右击鼠标");
		return;
	}

	dlg.DoModal();
	m_list.UpdateData(TRUE);
	UpdateList();
}

void CADODlg::OnButton1() 
{
	// TODO: Add your control notification handler code here
	CCreateTable m_ct;
	m_ct.DoModal();	
}

void CADODlg::OnSelect() 
{
	::CoInitialize(NULL);	// COM 初始化

	CSelectTable sel;
	if(2==sel.DoModal())
		return;

	memset(strOpen,0,100);
	sprintf(strOpen,"select name from syscolumns where id=(select max(id) from sysobjects where xtype='u' and name='%s')",tmp);
	_variant_t vname;
	int i = 0;
	g_totle = kk;
	try
	{
		m_list.DeleteAllItems();
		m_pRecordset.CreateInstance("ADODB.Recordset");
		//用SQL语句打开数据库“SELECT * FROM 表1”
		m_pRecordset->Open(strOpen, _variant_t((IDispatch*)theApp.m_pConnection,true), adOpenStatic, adLockOptimistic, adCmdText);
		while(!m_pRecordset->adoEOF)
		{
			vname = (_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t("Name"))->Value);
			WideCharToMultiByte(CP_ACP,0,vname.bstrVal,-1,g_totle,20,0,0);
			m_list.InsertColumn(i++, g_totle, LVCFMT_LEFT, 120);
			g_totle+=20;
			m_pRecordset->MoveNext();
		}
		m_list.SetExtendedStyle(LVS_EX_FULLROWSELECT);	//设置风格
	}
	catch(_com_error e)///捕捉异常
	{
		AfxMessageBox("读取数据库失败!");///显示错误信息
	}
	
	m_pRecordset->Close();

	sum1 = i;
	// 打开数据库
	try
	{
		memset(strOpen,0,100);
		sprintf(strOpen,"SELECT * FROM %s",tmp);
		m_pRecordset.CreateInstance("ADODB.Recordset");
		//用SQL语句打开数据库“SELECT * FROM 表1”
		m_pRecordset->Open(strOpen, _variant_t((IDispatch*)theApp.m_pConnection,true), adOpenStatic, adLockOptimistic, adCmdText);
		while(!m_pRecordset->adoEOF)
		{
			g_totle = kk;
			int nItem = m_list.InsertItem(0xffff,(_bstr_t)m_pRecordset->GetCollect(g_totle));
			for(int j=1;j<i;j++)
			{
				g_totle+=20;
				m_list.SetItem(nItem, j, 1, (_bstr_t)m_pRecordset->GetCollect(g_totle), NULL, 0, 0, 0);
			}
			m_pRecordset->MoveNext();
		}
	}
	catch(_com_error e)///捕捉异常
	{
		AfxMessageBox("读取数据库失败!");///显示错误信息
	}
	
	m_pRecordset->Close();
	//////////////////////////////////////////////////////////	
}

void CADODlg::OnButton3() 
{
	// TODO: Add your control notification handler code here
	CConnectInfo con;
	if(2 ==con.DoModal())
		return;
	
	memset(strOpen,0,100);
	sprintf(strOpen,"Provider=SQLOLEDB.1;Server=%s;Database=%s;uid=%s;pwd=%s",con.m_server,con.m_database,con.m_uid,con.m_pwd);

	if(!WriteDocFile(strOpen))
		MessageBox("修改失败!","提示",MB_OK);

	MessageBox("修改成功!","提示",MB_OK);
	UpdateList();
}

bool CADODlg::WriteDocFile(char* buffer)
{
	bool dwRet = TRUE;

	HRESULT hr;		// 函数执行返回值
	DWORD size;
	IStorage *pStg = NULL;	// 根存储接口指针
	IStorage *pSub = NULL;	// 子存储接口指针
	IStream *pStm = NULL;	// 流接口指针
	::CoInitialize(NULL);	// COM 初始化

	hr = ::StgCreateDocfile(	// 建立复合文件
		L"c:\\a.stg",	// 文件名称
		STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE,	// 打开方式
		0,		// 保留参数
		&pStg);		// 取得根存储接口指针
	ASSERT( SUCCEEDED(hr) );	// 为了突出重点,简化程序结构,所以使用了断言。
				// 在实际的程序中则要使用条件判断和异常处理

	hr = pStg->CreateStorage(	// 建立子存储
		L"SubStg",	// 子存储名称
		STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE,
		0,0,
		&pSub);		// 取得子存储接口指针
	ASSERT( SUCCEEDED(hr) );

	hr = pSub->CreateStream(	// 建立流
		L"Stm",		// 流名称
		STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE,
		0,0,
		&pStm);		// 取得流接口指针
	ASSERT( SUCCEEDED(hr) );

	
	hr = pStm->Write(		// 向流中写入数据
		buffer,		// 数据地址
		100,		// 字节长度(注意,没有写入字符串结尾的\0)
		&size);		// 不需要得到实际写入的字节长度
	if(!SUCCEEDED(hr))
	{
		dwRet = FALSE;
		goto exit;
	}

exit:

	if( pStm )	pStm->Release();// 释放流指针
	if( pSub )	pSub->Release();// 释放子存储指针
	if( pStg )	pStg->Release();// 释放根存储指针

	::CoUninitialize();		// COM 释放

	return dwRet;
}

void CADODlg::OnDelete() 
{
	// TODO: Add your command handler code here
	CString zz;
	if( m_list.GetSelectedCount() > 0)
	{
		POSITION pos = m_list.GetFirstSelectedItemPosition();
		int nSelected = m_list.GetNextSelectedItem(pos);
		zz = m_list.GetItemText(nSelected, 0);
	}
	else
	{
		AfxMessageBox("若要修改记录,必须在记录处右击鼠标");
		return;
	}

	CString csUpdate;
	csUpdate.Format("DELETE FROM %s WHERE %s='%s'",tmp,kk,zz);
	theApp.m_pConnection->Execute((LPCTSTR)csUpdate, NULL, adCmdText);
	UpdateList();	
}

void CADODlg::UpdateList()
{
	::CoInitialize(NULL);	// COM 初始化
	// 打开数据库
	try
	{
		m_list.DeleteAllItems();
		memset(strOpen,0,100);
		sprintf(strOpen,"SELECT * FROM %s",tmp);
		m_pRecordset.CreateInstance("ADODB.Recordset");
		//用SQL语句打开数据库“SELECT * FROM 表1”
		m_pRecordset->Open(strOpen, _variant_t((IDispatch*)theApp.m_pConnection,true), adOpenStatic, adLockOptimistic, adCmdText);
		while(!m_pRecordset->adoEOF)
		{
			g_totle = kk;
			int nItem = m_list.InsertItem(0xffff,(_bstr_t)m_pRecordset->GetCollect(g_totle));
			for(int j=1;j<sum1;j++)
			{
				g_totle+=20;
				m_list.SetItem(nItem, j, 1, (_bstr_t)m_pRecordset->GetCollect(g_totle), NULL, 0, 0, 0);
			}
			m_pRecordset->MoveNext();
		}
	}
	catch(_com_error e)///捕捉异常
	{
		AfxMessageBox("读取数据库失败!");///显示错误信息
	}
	
	m_pRecordset->Close();
}

⌨️ 快捷键说明

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