AVISO: Gracias por utilizar el servicio de
Traducción Automática. Este artículo ha sido traducido por un
sistema informático sin ayuda humana (Machine Translation).
Microsoft ofrece estos artículos a los usuarios que no comprendan el
inglés, exclusivamente, con el fin de que puedan entenderlos más
fácilmente. Microsoft no se hace responsable de la calidad
lingüística de las traducciones ni de la calidad técnica de los
contenidos de los artículos así como tampoco de cualesquiera
problemas, directos o indirectos, que pudieran surgir como
consecuencia de su utilización por los lectores.
Id. de artículo
:
180368
Última revisión
:
lunes, 14 de marzo de 2005
Versión
:
1.3
En esta página
Resumen
En este artículo muestra cómo obtener acceso y
actualizar campos de texto grande (Binary Large Objects/BLOBS) que
utilizan ActiveX Data Objects ( ADO ). Esto se realiza utilizando
los métodos del objeto de campo de un RecordSet de ADODB GetChunk y
AppendChunk.
Abra un proyecto nuevo. Se creará Form1 de
manera predeterminada
2.
En el menú Proyecto, haga clic en Referencias y
establezca una referencia a la Biblioteca de objetos de datos
de Microsoft ActiveX.
3.
Agregue un módulo estándar nuevo a su proyecto
y pegue el código siguiente:
Global cn As ADODB.Connection
Global cmd1 As ADODB.Command
Global rsset As ADODB.Recordset
Const BLOCKSIZE As Long = 4096
Public Sub ColumnToFile(Col As ADODB.Field, DiskFile As String)
'Retrieves data from the database and puts it into a temp file on
'the hard drive.
'The size of the chunk is in the variable BLOCKSIZE (4096).
Dim NumBlocks As Long 'Holds the number of chunks.
Dim LeftOver As Long '# of chars left over after last whole chunk.
Dim strData As String
Dim DestFileNum As Long
Dim I As Long
Dim ColSize As Long
'Make sure that you aren't in an empty recordset.
If Not rsset.EOF And Not rsset.BOF Then
ColSize = Col.ActualSize
'If filelength > 0, then it is soiled:
' throw away contents.
If Len(Dir$(DiskFile)) > 0 Then
Kill DiskFile
End If
DestFileNum = FreeFile
Open DiskFile For Binary As DestFileNum
NumBlocks = ColSize \ BLOCKSIZE
LeftOver = ColSize Mod BLOCKSIZE
'Now Write data to the file in chunks.
For I = 1 To NumBlocks
strData = String(BLOCKSIZE, 0)
strData = Col.GetChunk(BLOCKSIZE)
Put DestFileNum, , strData
Next I
strData = String(LeftOver, 0)
strData = Col.GetChunk(LeftOver)
Put DestFileNum, , strData
Close DestFileNum
End If
End Sub
Sub FileToColumn(Col As ADODB.Field, DiskFile As String)
'Takes data from the temp file and saves it to the database.
Dim strData As String
Dim NumBlocks As Long
Dim FileLength As Long
Dim LeftOver As Long
Dim SourceFile As Long
Dim I As Long
SourceFile = FreeFile
Open DiskFile For Binary Access Read As SourceFile
FileLength = LOF(SourceFile)
If FileLength = 0 Then
Close SourceFile
MsgBox DiskFile & " Empty or Not Found."
Else
NumBlocks = FileLength \ BLOCKSIZE
LeftOver = FileLength Mod BLOCKSIZE
Col.AppendChunk Null
strData = String(BLOCKSIZE, 0)
For I = 1 To NumBlocks
Get SourceFile, , strData
Col.AppendChunk strData
Next I
strData = String(LeftOver, 0)
Get SourceFile, , strData
Col.AppendChunk strData
rsset.Update
Close SourceFile
End If
End Sub
Public Sub FileToForm(DiskFile As String, SomeControl As Control)
'Retrieves data from the temp file and puts it onto the control.
Dim SourceFile As Long
Dim FileLength As Long
Dim strData As String
SourceFile = FreeFile
Open DiskFile For Binary Access Read As SourceFile
FileLength = LOF(SourceFile)
If FileLength = 0 Then
Close SourceFile
MsgBox DiskFile & " Empty or Not Found."
Else
strData = String(FileLength, 0)
Get SourceFile, , strData
SomeControl.Text = strData
Close SourceFile
End If
End Sub
Sub FormToFile(DiskFile As String, SomeControl As Control)
'Saves data from the form into a temp file on the local hard drive.
Dim DestinationFile As Long
Dim FileLength As Long
Dim strData As String
If Len(Dir$(DiskFile)) > 0 Then
Kill DiskFile
End If
DestinationFile = FreeFile
Open DiskFile For Binary As DestinationFile
strData = SomeControl.Text
Put DestinationFile, , strData
Close DestinationFile
End Sub
4.
Utilizar el valor predeterminado Form1:
a.
Agregue un control RichTextBox y
establezca su propiedad Name a "rtbText"
b.
Agregue un control CommandButton y
establezca su propiedad Name a "cmdPrev" y la propiedad
Título a "Prev."
c.
Agregue un control CommandButton y
establezca su propiedad Name a "cmdNext" y la propiedad
Título a "Siguiente"
d.
Agregue un control CommandButton y
establezca su propiedad Name a "cmdSave" y su propiedad
Título a "Actualización"
5.
Pegue el código siguiente en el
formulario:
Option Explicit
Dim DiskFile As String
Private Sub cmdNext_Click()
If (rsset.RecordCount > 0) And (Not rsset.EOF) Then
rsset.MoveNext
If Not rsset.EOF Then
rtbText.Text = ""
ColumnToFile rsset.Fields("pr_info"), DiskFile
FileToForm DiskFile, rtbText
Else
rsset.MoveLast
End If
End If
End Sub
Private Sub cmdPrev_Click()
If (rsset.RecordCount > 0) And (Not rsset.BOF) Then
rsset.MovePrevious
If Not rsset.BOF Then
rtbText.Text = ""
ColumnToFile rsset.Fields("pr_info"), DiskFile
FileToForm DiskFile, rtbText
Else
rsset.MoveFirst
End If
End If
End Sub
Private Sub cmdSave_Click()
FormToFile DiskFile, rtbText
FileToColumn rsset.Fields("pr_info"), DiskFile
End Sub
Private Sub Form_Activate()
rtbText.Text = ""
If rsset.RecordCount > 0 Then
rsset.MoveFirst
ColumnToFile rsset.Fields("pr_info"), DiskFile
FileToForm DiskFile, rtbText
End If
End Sub
Private Sub Form_Load()
Dim ConnectString As String
Dim anerror As ADODB.Error
Dim Sql As String
On Error GoTo handler
DiskFile = App.Path & "\BLOB.txt"
'Set the connect string to use pubs on your SQL server.
ConnectString = _
"Driver={SQL SERVER};Server=<yourserver>;Database=pubs;UID=sa;pwd=;"
Sql = "SELECT pr_info FROM pub_info;"
Set cn = New ADODB.Connection
cn.ConnectionString = ConnectString
cn.Open
Set rsset = New ADODB.Recordset
rsset.Open Sql, cn, adOpenKeyset, adLockOptimistic, adCmdText
Exit Sub
handler:
For Each anerror In cn.Errors
Debug.Print anerror.Number & ": " & anerror.Description & _
" - " & anerror.SQLState
Next anerror
End Sub
6.
Cambie el ServerName en el connectstring a su
nombre de servidor.
7.
Ejecute el proyecto de ejemplo. El control
RichTextBox contendrá el primer registro del conjunto de
registros.
8.
Haga clic en Siguiente. Observe que los
contenidos del control RichTextBox cambian al registro
siguiente hasta que llegue al último registro. El botón
Siguiente llama al método MoveNext del conjunto de registros y
después, llama a los métodos ColumnToFile y FileToForm.
9.
Haga clic en Prev. Observe que los contenidos
del control RichTextBox cambian al registro anterior hasta que
llegue al primer registro. El botón Prev llama al método
MovePrevious del conjunto de registros y después, llama a los
métodos ColumnToFile y FileToForm.
10.
Escriba algo nuevo en el cuadro de texto y a
continuación, haga clic en Actualizar para modificar el campo
de texto de cualquier registro en el que esté. El botón Update
llama a los métodos FormToFile y FileToColumn de llamar a vez
al método Update del conjunto de registros. Los datos nuevos
se deberían volver a actualizar en la base de datos.