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

📄 bolbdlg.cpp

📁 这是一个采用OLE DB编程处理的上传BLOB类型的二进制数据到数据库的一个实例
💻 CPP
字号:
// BOLBDlg.cpp : implementation file
//

#include "stdafx.h"
#include "BOLB.h"
#include "BOLBDlg.h"

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

void ShowImage(CDC *pDC,CString strFileName){
	IPicture *pPic; 
	IStream *pStm; 
	
	CFileStatus fstatus; 
	CFile file; 
	LONG cb; 
	
	if (file.Open(strFileName,CFile::modeRead)&&file.GetStatus(strFileName, 
		fstatus)&& 
		((cb = fstatus.m_size) != -1)) 
	{ 
		HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, cb); 
		LPVOID pvData = NULL; 
		if (hGlobal != NULL) 
		{ 
			if ((pvData = GlobalLock(hGlobal)) != NULL) 
			{ 
				file.ReadHuge(pvData, cb); 
				GlobalUnlock(hGlobal); 
				CreateStreamOnHGlobal(hGlobal, TRUE, &pStm); 
				
				if(SUCCEEDED(OleLoadPicture(pStm,fstatus.m_size,TRUE,IID_IPicture,(LPVOID* 
					)&pPic))) 
				{ 
					OLE_XSIZE_HIMETRIC hmWidth; 
					OLE_YSIZE_HIMETRIC hmHeight; 
					
					pPic->get_Width(&hmWidth); 
					pPic->get_Height(&hmHeight); 
					
					double fX,fY; 
					fX = (double)pDC->GetDeviceCaps(HORZRES)*(double)hmWidth/((double)pDC->GetDeviceCaps(HORZSIZE)*100.0); 
					fY = (double)pDC->GetDeviceCaps(VERTRES)*(double)hmHeight/((double)pDC->GetDeviceCaps(VERTSIZE)*100.0); 
					if(FAILED(pPic->Render(*pDC,0,0,(DWORD)fX,(DWORD)fY,0,hmHeight,hmWidth,-hmHeight,NULL))) 
						AfxMessageBox("Failed To Render The picture!"); 
					pPic->Release(); 
				} 
				else 
					;//AfxMessageBox("Error Loading Picture From Stream!"); 
			} 
		} 
	} 
	else 
		;//AfxMessageBox("Can't Open Image File!"); 
}
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()

/////////////////////////////////////////////////////////////////////////////
// CBOLBDlg dialog

CBOLBDlg::CBOLBDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CBOLBDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CBOLBDlg)
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CBOLBDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CBOLBDlg)
	DDX_Control(pDX, IDC_EDIT1, m_ctrEdit);
	DDX_Control(pDX, IDC_LIST1, m_list);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CBOLBDlg, CDialog)
	//{{AFX_MSG_MAP(CBOLBDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BuildStruct, OnBuildStruct)
	ON_BN_CLICKED(IDC_PushData, OnPushData)
	ON_BN_CLICKED(IDC_PopData, OnPopData)
	ON_LBN_SELCHANGE(IDC_LIST1, OnSelchangeList1)
	ON_LBN_DBLCLK(IDC_LIST1, OnDblclkList1)
	ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CBOLBDlg message handlers

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

void CBOLBDlg::OnBuildStruct() 
{
	// TODO: Add your control notification handler code here
	CSypODLConnection con;
	con.OpenWithConnectionString(this->m_hWnd);
	con.m_bEnableThrow=FALSE;
	con.Execute("Create Table MyPicTest(remark varchar(200),pic image)");
	con.Execute("Create Table MyPicTest(remark varchar(200),pic BLOB)");
	con.Execute("Create Table MyPicTest(remark varchar(200),pic long binery)");
	con.ClearErrors();
	con.Close();
}

#define _BLOB_ENTRY_CODE_EX(nOrdinal, IID, flags, dataOffset, lengthOffset, statusOffset) \
	if (pBuffer != NULL) \
	{ \
		CAccessorBase::FreeType(DBTYPE_IUNKNOWN, pBuffer + dataOffset); \
	} \
	else if (pBinding != NULL) \
	{ \
		DBOBJECT* pObject = NULL; \
		ATLTRY(pObject = new DBOBJECT); \
		if (pObject == NULL) \
			return E_OUTOFMEMORY; \
		pObject->dwFlags = flags; \
		pObject->iid     = IID; \
		CAccessorBase::Bind(pBinding, nOrdinal, DBTYPE_IUNKNOWN, sizeof(IUnknown*), 0, 0, eParamIO, \
			dataOffset, lengthOffset, statusOffset, pObject); \
		pBinding++; \
	} \
	nColumns++;
#define BLOB_ENTRY_LENGTH_STATUS(nOrdinal, IID, flags, data, length, status) \
	_BLOB_ENTRY_CODE_EX(nOrdinal, IID, flags, offsetbuf(data), offsetbuf(length), offsetbuf(status))

class PicAccessor
{
public:
	TCHAR m_szRemark[200];
	ISequentialStream *m_BLOBDATA;
	
	ULONG m_BLOBDATA_LENGTH;
	ULONG m_BLOBDATA_STATUS;
	
	BEGIN_COLUMN_MAP(PicAccessor)
		COLUMN_ENTRY(1,m_szRemark)
		BLOB_ENTRY_LENGTH_STATUS(2, IID_ISequentialStream, 
						 STGM_READ, m_BLOBDATA, 
						 m_BLOBDATA_LENGTH, m_BLOBDATA_STATUS)
	END_COLUMN_MAP()
	
	void ClearRecord()
	{
		memset(this, 0, sizeof(*this));
	}
};

class PicAccessor1
{
public:
	TCHAR m_szRemark[200];
	
	BEGIN_COLUMN_MAP(PicAccessor1)
		COLUMN_ENTRY(1,m_szRemark)
	END_COLUMN_MAP()
	
	void ClearRecord()
	{
		memset(this, 0, sizeof(*this));
	}
};
class PicsCountAccessor
{
public:
	ULONG m_RecordCounts;
	
	BEGIN_COLUMN_MAP(PicsCountAccessor)
		COLUMN_ENTRY(1,m_RecordCounts)
	END_COLUMN_MAP()
	
	void ClearRecord()
	{
		memset(this, 0, sizeof(*this));
	}
};
void CBOLBDlg::OnPushData()
{
	BeginWaitCursor();
	CFileDialog fd(TRUE);
	if(fd.DoModal()!=IDOK)return;
	CSypODLConnection con;
	con.OpenWithConnectionString(m_hWnd);

	CSypODLRecordBase <CAccessor<PicsCountAccessor> > pica_countor;

	CString strGetCountsSQL;
	strGetCountsSQL.Format("SELECT COUNT(remark) AS pic_counts FROM MyPicTest");
	CDBPropSet   propset_count(DBPROPSET_ROWSET);
	HRESULT hr = pica_countor.Open(&propset_count,strGetCountsSQL,&con);
	if(FAILED(hr)){
		AfxMessageBox("没有找到数据表MyPicTest");
		EndWaitCursor();
		return;
	}

	ULONG lRecordsCount=pica_countor.GetAccessor()->m_RecordCounts;
	pica_countor.Close();


	con.StartTransaction();
	
	CSypODLRecordBase <CAccessor<PicAccessor> > pica;


	CString strSql;
	strSql.Format("SELECT * FROM MyPicTest");
	
	CDBPropSet   propset(DBPROPSET_ROWSET);
    propset.AddProperty(DBPROP_IRowsetChange, true);
    propset.AddProperty(DBPROP_UPDATABILITY,
                        DBPROPVAL_UP_CHANGE |
                        DBPROPVAL_UP_INSERT |
                        DBPROPVAL_UP_DELETE);

	
	hr = pica.Open(&propset,strSql,&con);
	if(FAILED(hr)){
		AfxMessageBox("没有找到数据表MyPicTest");
		EndWaitCursor();
		return;
	}

	if(lRecordsCount>0)pica.GetAccessor()->m_BLOBDATA->Release();
	
	pica.GetAccessor()->ClearRecord();

	CString strFileName=fd.GetFileName();
	
	lstrcpy(pica.GetAccessor()->m_szRemark,strFileName.GetBuffer(strFileName.GetLength()));
	
	ULONG nCountRead=200L;
	ULONG nCountWriten=0L;

	char buf[200];
	
	CISSHelper blobData;
	
	CFile chunkf(strFileName,CFile::modeRead);
	while(nCountRead==200){
		nCountRead=0L;
		nCountRead=chunkf.Read(buf,200);
		if(nCountRead>0&&nCountRead<201)blobData.Write(buf,nCountRead,&nCountWriten);
	}
	chunkf.Close();	

	pica.GetAccessor()->m_BLOBDATA_LENGTH = blobData.m_ulLength;
	pica.GetAccessor()->m_BLOBDATA_STATUS = DBSTATUS_S_OK;

	pica.GetAccessor()->m_BLOBDATA=(ISequentialStream *)(&blobData);

	if(!(pica.Insert())){
		pica.FreeRecordMemory();
		UpdateData(FALSE);
		EndWaitCursor();
		MessageBox("入库失败");
		return;
	}

	pica.FreeRecordMemory();
	
	con.Commit();
	pica.Close();
	con.Close();
	
	m_ctrEdit.ShowImage(strFileName);
	UpdateData(FALSE);
	EndWaitCursor();
}

void CBOLBDlg::OnPopData() 
{
	BeginWaitCursor();
	CSypODLConnection con;
	con.OpenWithConnectionString(m_hWnd);
	con.StartTransaction();
	CSypODLRecordBase <CAccessor<PicAccessor1> > pica;
	CString strSql;
	strSql.Format("SELECT remark FROM MyPicTest");

	HRESULT hr = pica.Open(strSql,&con);
	if(FAILED(hr)){
		AfxMessageBox("没有找到数据表MyPicTest");
		EndWaitCursor();
		return;
	}
	ULONG ulRecordCount=pica.GetRecordCount();
	m_list.ResetContent();
	for(ULONG ul=0;ul<ulRecordCount;ul++){
		m_list.AddString(pica.GetAccessor()->m_szRemark);
		pica.MoveNext();
	}
	pica.Close();
	con.Close();
	UpdateData(FALSE);
	EndWaitCursor();
}

void CBOLBDlg::OnSelchangeList1() 
{
	BeginWaitCursor();
	UpdateData();
	int iCur=m_list.GetCurSel();

	CString strPicName;
	m_list.GetText(iCur,strPicName);

	CSypODLConnection con;
	con.OpenWithConnectionString(m_hWnd);
	con.StartTransaction();
	CSypODLRecordBase <CAccessor<PicAccessor> > pica;
	CString strSql;
	strSql.Format("SELECT * FROM MyPicTest where remark = '%s'",
		strPicName.GetBuffer(strPicName.GetLength()));

	HRESULT hr = pica.Open(strSql,&con);
	if(FAILED(hr)){
		AfxMessageBox("没有找到数据表MyPicTest");
		EndWaitCursor();
		return;
	}
		
	ULONG nCountRead=200L;
	ULONG nCountWriten=0L;

	char buf[200];
	
	CString strFileName=_T("c:\\abcd.jpg");
	DeleteFile("c:\\abcd.jpg");
	CFile chunkf(strFileName,CFile::modeWrite|CFile::modeCreate);
	while(nCountRead==200){
		nCountRead=0L;
		pica.GetAccessor()->m_BLOBDATA->Read(buf,200,&nCountRead);
		if(nCountRead>0&&nCountRead<201)chunkf.Write(buf,nCountRead);
	}
	chunkf.Close();	

//	pica.FreeRecordMemory();
	pica.GetAccessor()->m_BLOBDATA->Release();
	
	pica.Close();
	con.Close();

	m_ctrEdit.ShowImage(strFileName);
	UpdateData(FALSE);
	EndWaitCursor();
}

void CBOLBDlg::OnDblclkList1() 
{
	BeginWaitCursor();
	UpdateData();
	int iCur=m_list.GetCurSel();

	CString strPicName;
	m_list.GetText(iCur,strPicName);

	CSypODLConnection con;
	con.OpenWithConnectionString(m_hWnd);
	con.StartTransaction();
	CSypODLRecordBase <CAccessor<PicAccessor> > pica;
	CString strSql;
	strSql.Format("SELECT * FROM MyPicTest where remark = '%s'",
		strPicName.GetBuffer(strPicName.GetLength()));

	HRESULT hr = pica.Open(strSql,&con);
	if(FAILED(hr)){
		AfxMessageBox("没有找到数据表MyPicTest");
		EndWaitCursor();
		return;
	}
		
	ULONG nCountRead=200L;
	ULONG nCountWriten=0L;

	char buf[200];
	
	CString strFileName=_T("c:\\abcd.jpg");
	DeleteFile("c:\\abcd.jpg");
	CFile chunkf(strFileName,CFile::modeWrite|CFile::modeCreate);
	while(nCountRead==200){
		nCountRead=0L;
		pica.GetAccessor()->m_BLOBDATA->Read(buf,200,&nCountRead);
		if(nCountRead>0&&nCountRead<201)chunkf.Write(buf,nCountRead);
	}
	chunkf.Close();	
//	pica.FreeRecordMemory();

	pica.GetAccessor()->m_BLOBDATA->Release();


	pica.Close();	
	con.Close();

	m_ctrEdit.ShowImage(strFileName);
	UpdateData(FALSE);
	EndWaitCursor();
}

void CBOLBDlg::OnButton1() 
{
	CSypODLConnection con;
	con.SetupConnectionString(m_hWnd);
	con.Close();
}

⌨️ 快捷键说明

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