Artigo: 103257 - Última revisão: quinta-feira, 18 de Janeiro de 2007 - Revisão: 2.3

ACC: Ler, armazenar & Writing Binary Large Objects (BLOBs)

Dica do SistemaEste artigo aplica-se a um sistema operativo diferente do que está a utilizar. Foi desactivado o conteúdo do artigo, que pode não ser relevante para si.
Avançado: Requer conhecimentos avançados sobre codificação, interoperabilidade e multi-utilizador.

Expandir tudo | Reduzir tudo

Sumário

Pode armazenar objectos de dados grandes (tais como dados de som, vídeo ou de gráficos) num campo com o tipo de dados objecto OLE numa tabela do Microsoft Access. Alguns objectos de dados binários grandes não podem ser representados, no entanto, se não tiver um servidor OLE que compreende os dados que está a ser armazenados. Também é possível armazenar cópias dos ficheiros de programa executável ou outros dados não OLE numa tabela do Microsoft Access. Este tipo de dados é referido como um mapa de bits objectos grandes binários (BLOB).

Este artigo pressupõe que está familiarizado com o Visual Basic for Applications e criação de aplicações do Microsoft Access utilizando as ferramentas de programação fornecidas com o Microsoft Access. Para mais informações sobre o Visual Basic for Applications, consulte a versão do manual "Criar aplicações com o Microsoft Access".

NOTA: Visual Basic for Applications é designado por Basic do Access no Microsoft Access versões 1.x e 2.0. Para mais informações sobre o Basic do Access, consulte o manual "Introdução à programação" na versão 1.x do Microsoft Access ou o manual "Building Applications" no Microsoft Access versão 2.0.

Mais Informação

O exemplo seguinte contém dois exemplo funções definidas pelo utilizador que pode utilizar para gerir grandes quantidades de dados binários num campo com o tipo de dados objecto OLE. As funções definidas pelo utilizador são ReadBLOB() e WriteBLOB().

  • A função ReadBLOB() lê um ficheiro binário do disco e armazena-num campo Objecto OLE.
  • A escrita de função WriteBLOB() dados binários armazenados um objecto OLE de campo para um ficheiro no disco.
Este exemplo demonstra como copiar um ficheiro binário para um campo Objecto OLE e como escrever-cópia de segurança para um novo ficheiro de disco:

  1. Criar um novo módulo chamado BLOB e introduza as seguintes linhas na secção de declarações o módulo:
    Opção explícita
    BlockSize constante = 32768
    NOTA: Se estiver a trabalhar com o Microsoft Access 2.0, é necessário incluir as seguintes definições após as anteriores duas:
          Const dbOpenTable = DB_OPEN_TABLE
          Const acSysCmdInitMeter = SYSCMD_INITMETER
          Const acSysCmdUpdateMeter = SYSCMD_UPDATEMETER
          Const acSysCmdRemoveMeter = SYSCMD_REMOVEMETER
  2. Introduza o código seguinte no módulo.

    NOTA: No código de exemplo seguinte, um sublinhado (_) no final de uma linha é utilizado como um carácter de continuação de linha. Remova o carácter de sublinhado do final da linha quando recriar este código Basic do Access.

    NOTA: A técnica seguinte não irá funcionar para o Microsoft Access 1.x. Para o Microsoft Access 1.x, terá de modificar o código para que utilize tabela de variáveis em vez de variáveis de conjunto de registos e a AbrirTabela função em vez de OpenRecordset.
          '**************************************************************
          ' FUNCTION: ReadBLOB()
          '
          ' PURPOSE:
          '   Reads a BLOB from a disk file and stores the contents in the
          '   specified table and field.
          '
          ' PREREQUISITES:
          '   The specified table with the OLE object field to contain the
          '   binary data must be opened in Visual Basic code (Access Basic
          '   code in Microsoft Access 2.0 and earlier) and the correct record
          '   navigated to prior to calling the ReadBLOB() function.
          '
          ' ARGUMENTS:
          '   Source - The path and filename of the binary information
          '            to be read and stored.
          '   T      - The table object to store the data in.
          '   Field  - The OLE object field in table T to store the data in.
          '
          ' RETURN:
          '   The number of bytes read from the Source file.
          '**************************************************************
          Function ReadBLOB(Source As String, T As Recordset, _
          sField As String)
              Dim NumBlocks As Integer, SourceFile As Integer, i As Integer
              Dim FileLength As Long, LeftOver As Long
              Dim FileData As String
              Dim RetVal As Variant
    
              On Error GoTo Err_ReadBLOB
    
              ' Open the source file.
              SourceFile = FreeFile
              Open Source For Binary Access Read As SourceFile
    
              ' Get the length of the file.
              FileLength = LOF(SourceFile)
              If FileLength = 0 Then
                  ReadBLOB = 0
                  Exit Function
              End If
    
              ' Calculate the number of blocks to read and leftover bytes.
              NumBlocks = FileLength \ BlockSize
              LeftOver = FileLength Mod BlockSize
    
              ' SysCmd is used to manipulate status bar meter.
              RetVal = SysCmd(acSysCmdInitMeter, "Reading BLOB", _
                       FileLength \ 1000)
    
              ' Put the record in edit mode.
              T.Edit
    
              ' Read the leftover data, writing it to the table.
              FileData = String$(LeftOver, 32)
              Get SourceFile, , FileData
              T(sField).AppendChunk (FileData)
    
              RetVal = SysCmd(acSysCmdUpdateMeter, LeftOver / 1000)
    
              ' Read the remaining blocks of data, writing them to the table.
              FileData = String$(BlockSize, 32)
              For i = 1 To NumBlocks
                  Get SourceFile, , FileData
                  T(sField).AppendChunk (FileData)
    
                  RetVal = SysCmd(acSysCmdUpdateMeter, BlockSize * i / 1000)
              Next i
    
              ' Update the record and terminate function.
              T.Update
              RetVal = SysCmd(acSysCmdRemoveMeter)
              Close SourceFile
              ReadBLOB = FileLength
              Exit Function
    
          Err_ReadBLOB:
              ReadBLOB = -Err
              Exit Function
    
          End Function
    
          '**************************************************************
          ' FUNCTION: WriteBLOB()
          '
          ' PURPOSE:
          '   Writes BLOB information stored in the specified table and field
          '   to the specified disk file.
          '
          ' PREREQUISITES:
          '   The specified table with the OLE object field containing the
          '   binary data must be opened in Visual Basic code (Access Basic
          '   code in Microsoft Access 2.0 or earlier) and the correct
          '   record navigated to prior to calling the WriteBLOB() function.
          '
          ' ARGUMENTS:
          '   T           - The table object containing the binary information.
          '   sField      - The OLE object field in table T containing the
          '                 binary information to write.
          '   Destination - The path and filename to write the binary
          '                 information to.
          '
          ' RETURN:
          '   The number of bytes written to the destination file.
          '**************************************************************
          Function WriteBLOB(T As Recordset, sField As String, _
          Destination As String)
              Dim NumBlocks As Integer, DestFile As Integer, i As Integer
              Dim FileLength As Long, LeftOver As Long
              Dim FileData As String
              Dim RetVal As Variant
    
              On Error GoTo Err_WriteBLOB
    
              ' Get the size of the field.
              FileLength = T(sField).FieldSize()
              If FileLength = 0 Then
                  WriteBLOB = 0
                  Exit Function
              End If
    
              ' Calculate number of blocks to write and leftover bytes.
              NumBlocks = FileLength \ BlockSize
              LeftOver = FileLength Mod BlockSize
    
              ' Remove any existing destination file.
              DestFile = FreeFile
              Open Destination For Output As DestFile
              Close DestFile
    
              ' Open the destination file.
              Open Destination For Binary As DestFile
    
              ' SysCmd is used to manipulate the status bar meter.
              RetVal = SysCmd(acSysCmdInitMeter, _
              "Writing BLOB", FileLength / 1000)
    
              ' Write the leftover data to the output file.
              FileData = T(sField).GetChunk(0, LeftOver)
              Put DestFile, , FileData
    
              ' Update the status bar meter.
              RetVal = SysCmd(acSysCmdUpdateMeter, LeftOver / 1000)
    
              ' Write the remaining blocks of data to the output file.
              For i = 1 To NumBlocks
                  ' Reads a chunk and writes it to output file.
                  FileData = T(sField).GetChunk((i - 1) * BlockSize _
                     + LeftOver, BlockSize)
                  Put DestFile, , FileData
    
                  RetVal = SysCmd(acSysCmdUpdateMeter, _
                  ((i - 1) * BlockSize + LeftOver) / 1000)
              Next i
    
              ' Terminates function
              RetVal = SysCmd(acSysCmdRemoveMeter)
              Close DestFile
              WriteBLOB = FileLength
              Exit Function
    
          Err_WriteBLOB:
              WriteBLOB = -Err
              Exit Function
    
          End Function
    
          '**************************************************************
          ' SUB: CopyFile
          '
          ' PURPOSE:
          '   Demonstrates how to use ReadBLOB() and WriteBLOB().
          '
          ' PREREQUISITES:
          '   A table called BLOB that contains an OLE Object field called
          '   Blob.
          '
          ' ARGUMENTS:
          '   Source - The path and filename of the information to copy.
          '   Destination - The path and filename of the file to write
          '                 the binary information to.
          '
          ' EXAMPLE:
          '   CopyFile "c:\windows\winfile.hlp", "c:\windows\winfil_1.hlp"
          '**************************************************************
          Sub CopyFile(Source As String, Destination As String)
              Dim BytesRead As Variant, BytesWritten As Variant
              Dim Msg As String
              Dim db As Database
              Dim T As Recordset
    
              ' Open the BLOB table.
              Set db = CurrentDb()
              Set T = db.OpenRecordset("BLOB", dbOpenTable)
    
              ' Create a new record and move to it.
              T.AddNew
              T.Update
              T.MoveLast
    
              BytesRead = ReadBLOB(Source, T, "Blob")
    
              Msg = "Finished reading """ & Source & """"
              Msg = Msg & Chr$(13) & ".. " & BytesRead & " bytes read."
              MsgBox Msg, 64, "Copy File"
    
              BytesWritten = WriteBLOB(T, "Blob", Destination)
    
              Msg = "Finished writing """ & Destination & """"
              Msg = Msg & Chr$(13) & ".. " & BytesWritten & " bytes written."
              MsgBox Msg, 64, "Copy File"
          End Sub
    						
  3. Crie a seguinte nova tabela e, em seguida, guardá-lo como BLOB:
          Table: BLOB
          ------------------------
          Field Name: Blob
             Data Type: OLE Object
  4. Com o módulo BLOB aberto na vista de estrutura, clique em janela de depuração (ou janela Immediate no Microsoft Access 2.0 ou anterior) no menu Ver.
  5. Escreva a seguinte linha na janela de depuração e, em seguida, prima ENTER:
          CopyFile "c:\windows\winfile.hlp", "c:\windows\winfil_1.hlp"
As funções ReadBLOB() e WriteBLOB() copiar o ficheiro de ajuda do Microsoft Windows para o campo BLOB na tabela de BLOB e, em seguida, a partir daí para um ficheiro no disco chamado Winfil_1.hlp

A informação contida neste artigo aplica-se a:
  • Microsoft Access 1.0 Standard Edition
  • Microsoft Access 1.1 Standard Edition
  • Microsoft Access 2.0 Standard Edition
  • Microsoft Access 95 Standard Edition
  • Microsoft Access 97 Standard Edition
Palavras-chave: 
kbmt kbinfo kbprogramming KB103257 KbMtpt
Tradução automáticaTradução automática
IMPORTANTE: Este artigo foi traduzido por um sistema de tradução automática (também designado por Machine translation ou MT), não tendo sido portanto revisto ou traduzido por humanos. A Microsoft tem artigos traduzidos por aplicações (MT) e artigos traduzidos por tradutores profissionais. O objectivo é simples: oferecer em Português a totalidade dos artigos existentes na base de dados do suporte. Sabemos no entanto que a tradução automática não é sempre perfeita. Esta pode conter erros de vocabulário, sintaxe ou gramática? erros semelhantes aos que um estrangeiro realiza ao falar em Português. A Microsoft não é responsável por incoerências, erros ou estragos realizados na sequência da utilização dos artigos MT por parte dos nossos clientes. A Microsoft realiza actualizações frequentes ao software de tradução automática (MT). Obrigado.
Clique aqui para ver a versão em Inglês deste artigo: 103257  (http://support.microsoft.com/kb/103257/en-us/ )
Retired KB ArticleExclusão de Responsabilidade para Conteúdo sem Suporte na KB
Este artigo foi escrito sobre produtos para os quais a Microsoft já não fornece suporte. Por conseguinte, este artigo é oferecido "tal como está" e deixará de ser actualizado.