前文说到用AppendChunck和GetChunck方法,但是Stream方法更为方便。因为前一种方法需要单独定义读文件的操作,还需要定义缓冲区来保存数据。而Stream方法直接实现文件和流之间的转换,甚是快捷。
1. 将文件数据存储到数据库中
void
CFileOperDlg::OnBnClickedButtonInsert()
{
// TODO:
在此添加控件通知处理程序代码
_RecordsetPtr pRecordset( __uuidof(Recordset) );
CString strSql = _T( "select * from /"userinfo/"" );
try
{
_bstr_t varSql( strSql );
//
打开记录集
HRESULT hr = pRecordset->Open( varSql, m_pConnection.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText );
if ( FAILED( hr ) )
{
AfxMessageBox( _T( "
打开记录集失败!"
) );
return ;
}
}
catch (_com_error & e)
{
AfxMessageBox(e.Description());
return ;
}
pRecordset->AddNew(); ///
添加新记录
pRecordset->PutCollect("id",_variant_t(12));
pRecordset->PutCollect("username", _variant_t( "Owen" ) );
pRecordset->PutCollect("old", _variant_t( 24 ) );
_StreamPtr oStream( __uuidof( Stream ) );
oStream->Type = adTypeBinary; //
设置为二进制数据
_variant_t varOptional(DISP_E_PARAMNOTFOUND,VT_ERROR);
//
打开流
oStream->raw_Open(varOptional, adModeUnknown, adOpenStreamUnspecified,NULL,NULL);
//
将文件转换成流
oStream->LoadFromFile( _T( "
文件全路径"
) );
//
给二进制字段赋值
pRecordset->GetFields()->GetItem( "photo" )->Value = oStream->Read( oStream->GetSize() );
pRecordset->Update( vtMissing, vtMissing );
if ( pRecordset != NULL && pRecordset->GetState() == adStateOpen )
{
pRecordset->Close();
}
pRecordset.Release();
oStream.Release();
}
2. 将数据库中数据存储成文件
void
CFileOperDlg::OnBnClickedButtonDownload()
{
// TODO:
在此添加控件通知处理程序代码
_RecordsetPtr pRecordset( __uuidof(Recordset) );
CString strSql = _T( "select * from /"userinfo/" where id = 12" );
try
{
_bstr_t varSql( strSql );
//
打开记录集
HRESULT hr = pRecordset->Open( varSql, m_pConnection.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText );
if ( FAILED( hr ) )
{
AfxMessageBox( _T( "
打开记录集失败!"
) );
return ;
}
}
catch (_com_error & e)
{
AfxMessageBox(e.Description());
return ;
}
_StreamPtr oStream( __uuidof( Stream ) );
oStream->Type = adTypeBinary; //
二进制数据
_variant_t varOptional(DISP_E_PARAMNOTFOUND,VT_ERROR);
//
打开流
oStream->raw_Open(varOptional, adModeUnknown, adOpenStreamUnspecified,NULL,NULL);
//
向流中写数据
oStream->Write( pRecordset->GetFields()->GetItem( "photo" )->Value );
//
保存成文件
oStream->SaveToFile( _T( "
文件全路径"
), adSaveCreateOverWrite );
if ( pRecordset != NULL && pRecordset->GetState() == adStateOpen )
{
pRecordset->Close();
}
pRecordset.Release();
oStream.Release();
}