Click here to Skip to main content
Click here to Skip to main content

Using CLongBinary for BLOBs

By , 30 Nov 1999
 
  • Download demo project - 29 Kb
  • Sample Image - UsingBlob.gif

    At times, storing images and other types of documents like word document, or excel spread sheet or even a compressed zip file in the database is inevitable. MFC provides a supporting class to handle these BLOBs called CLongBinary. It is just a wrapper around the HGLOBAL of WIN32. But how do you use it? The wizard creates a member variable of type CLongBinary in your record set object and also creates the corresponding RFX routine (RFX_LongBinary).

    Okay, does it mean that you can use this member just like any other variable? No, That's where this document comes in handy. For regular data types, all you have to is create an instance of the recordset object, assign the values and call Update. But for BLOBs, you have to do something special. For inserting BLOBs, you have to remember 3 points.

    1. Allocate and lock the storage buffer using GlobalAlloc() and GlobalLock() calls
    2. Prepare the recordset for blob operation using SetFieldDirty() and SetFieldNull() calls
    3. Unlock the storage buffer

    By default, the destructor of the CLongBinary will delete the buffer using GlobalFree() call. So you don't have to bother about freeing the memory. Reading from the database is pretty simple. All you have to do is lock the buffer.

    Following code snippet shows how to do this in the actual code:

    // Store the Image to database table
    // 
    try
    {
        dbImages.Open();
        dbImages.AddNew();
    
        CFile	fileImage;
        CFileStatus	fileStatus;
    
        fileImage.Open("c:\\winnt\\winnt256.bmp", CFile::modeRead);
        fileImage.GetStatus(fileStatus);
    
        dbImages.m_BLOBName = fileImage.GetFileTitle();
        dbImages.m_BLOBImage.m_dwDataLength = fileStatus.m_size;
    
        HGLOBAL hGlobal		= GlobalAlloc(GPTR,fileStatus.m_size);
        dbImages.m_BLOBImage.m_hData = GlobalLock(hGlobal);
    
        fileImage.ReadHuge(dbImages.m_BLOBImage.m_hData,fileStatus.m_size);
    
        dbImages.SetFieldDirty(&dbImages.m_BLOBImage);
        dbImages.SetFieldNull(&dbImages.m_BLOBImage,FALSE);
        dbImages.Update();
    
        GlobalUnlock(hGlobal);
    
        dbImages.Close();
    
        pList->InsertItem(0,fileImage.GetFileTitle());
    }
    catch(CException* pE)
    {
        pE->ReportError();
        pE->Delete();
        return;
    }

     

    // To restore image from db table
    CdbImages   dbImages(&theApp.m_DB);
    CString     strFileName = pList->GetItemText(nIndex,0);
    dbImages.m_strFilter.Format("BLOBName = '%s'",strFileName);
    try
    {
        dbImages.Open();
        if  (dbImages.IsEOF())
            AfxMessageBox("Unable to get image from db");
        else
        {
            char    tmpPath[_MAX_PATH+1];
            GetTempPath(_MAX_PATH,tmpPath);
    
            strFileName.Insert(0,tmpPath);
            
            CFile	outFile(strFileName,CFile::modeCreate|CFile::modeWrite);
            LPSTR	buffer = (LPSTR)GlobalLock(dbImages.m_BLOBImage.m_hData);
            outFile.WriteHuge(buffer,dbImages.m_BLOBImage.m_dwDataLength);
            GlobalUnlock(dbImages.m_BLOBImage.m_hData);
            outFile.Close();
    
            theApp.OpenDocumentFile(strFileName);
        }
    
        dbImages.Close();
    
    }
    catch(CException* pE)
    {
        pE->ReportError();
        pE->Delete();
        return;
    }
    
    

    The demo project uses an Access database to store the images. This project also demonstrates the following:

    • DSN - less Connection to MS Access database
    • Dialog Bars
    • Image Display in CScrollView

    The images are displayed using the simplest technique of using BitBlt() call. It does not use any Palettes because it is beyond the scope of this article.

    License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here

    About the Author

    Shekar Narayanan
    United States United States
    Member
    No Biography provided

    Sign Up to vote   Poor Excellent
    Add a reason or comment to your vote: x
    Votes of 3 or less require a comment

    Comments and Discussions

     
    You must Sign In to use this message board.
    Search this forum  
        Spacing  Noise  Layout  Per page   
    GeneralMy vote of 5memberMember 41790757 Aug '11 - 10:56 
    good
    QuestiondbImages.Open() is taking 100% CPU usage??memberGokulnath00715 Jul '11 - 1:15 
    dbImages.Open() is taking 100% CPU usage??
    QuestionDynamic Table namememberMember 799544422 Jun '11 - 18:05 
    Hi,
     
    I have to update a blob data into db but with tables that dynamically change. could you please help in this.
    GeneralProblem with Recordset.Open(CRecordset::snapshot,_T("SELECT * FROM TEST")) functionmembernavneet.professional5 May '10 - 0:50 
    Hi,
     
    I am trying to save .txt file using CLongBinary class.
    I am using Interbase 6.0 database.Database connection is successfully made using following code:
     
    CString ServerConnectingString;
    ServerConnectingString.Format("DSN=ServerDatabase;UID=SYSDBA;PWD=masterkey");
     
    try
    {
       pServerDatabase->OpenEx(ServerConnectingString,CDatabase::noOdbcDialog);
    }
     
    I have also read "1.txt" file & stored in CLongBinary pointer same as mentioned in sample code.But when i am trying to open recordset with following code:
    CRecordset rsSDetails(pApp->pServerDatabase);
    rsSDetails.Open(CRecordset::snapshot,_T("SELECT * FROM TEST"));
    Then following errors are displayed:
     
    CDBException e.m_strError = "Driver does not support this function"
    CDBException e.m_strStateNativeOrigin =    
    {"State:IM001,NativeBlush | :O ,Origin:[Microsoft][ODBC Driver Manager]
    "}
     
    Please help me out. I tried many times, but it is not working.
    Please reply me any workaround to fix it as soon as possible.
     
    Thanks
    Generalerror C2039: 'WriteHuge' : is not a member of 'CFile' g:\mainfrm.cpp and Error and error C2039: 'ReadHuge' : is not a member of 'CFile' g:\mainfrm.cpp 205memberKYAW KYAW OO31 Jul '08 - 17:49 
    Dear Narayanan,
     

    First of all, I would like to say, thank you for your contribution in here.
     
    I am a begineer of image processing and database. I found out the above error and tried to solve it myself but still there.
     
    I will be looking forward to hearing from your advice.
     

     
    Thanks and best regards
    Ko Ko
    GeneralRe: error C2039: 'WriteHuge' : is not a member of 'CFile' g:\mainfrm.cpp and Error and error C2039: 'ReadHuge' : is not a member of 'CFile' g:\mainfrm.cpp 205memberRolando E. Cruz-Marshall26 Sep '08 - 2:04 
    D'Oh! | :doh: If you'd search for "WriteHuge" with your MS Visual Studio Documentation you will notice it states that method is now obsolete. At the time this article was written WriteHuge was available at the time.
     
    Code still works...
     
    Rolando Suspicious | :suss:

    GeneralReally Goodmembermanish rastogi2 Jul '08 - 23:48 
    It is really good.
    Thanks Shekar Narayanan. Smile | :)
    Generalsome question about insert images,please tell me!memberfreesky32325 Jan '07 - 3:03 
    how to insert images into oracle using BLOB?
    Questionnew recordmemberali212121212121219 May '06 - 4:36 
    How to add a record for descriping the picture?Confused | :confused:
    Questionhow to insert image to SQL servermemberthanhthuyvn_vtajkhskjakjd12 Nov '05 - 20:18 
    how to insert image to SQL server?
    thanks for your help.
     
    An Phung Nguyen

    General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

    Permalink | Advertise | Privacy | Mobile
    Web01 | 2.6.130523.1 | Last Updated 1 Dec 1999
    Article Copyright 1999 by Shekar Narayanan
    Everything else Copyright © CodeProject, 1999-2013
    Terms of Use
    Layout: fixed | fluid