开发者

Retrieving Binary data from SQL in VB6

If you have a column of type binary in SQL and return it using ADODB in VB6 even if the column contains only 1 byte of data it must be stored as a byte array.

So for example:

Dim cm As ADODB.Command
Dim rs As ADODB.Recordset

Set cm = New ADODB.Command
Set rs = New ADODB.Recordset

With cm
    .ActiveConnection = cn
    .CommandTimeout = 30
    .CommandType = adCmdText
    .CommandText = "SELECT * FROM Table WHERE RowID = ?"
    .Parameters.Append .CreateParameter("TableID", adInteger, adParamInput, , TableID)
End With

RecordsetOpen cn, rs, cm, , adOpenForwardOnly, adLockReadOnly

With rs
    If .State = adStateOpen Then
        If .RecordCount >开发者_开发问答; 0 Then
            Dim tempArray() As Byte
            tempArray = .Fields("BinaryColumn")
            ''Success! Returns array containing 1 Byte in it

            Dim value as Byte
            value = .Fields("BinaryColumn")
            ''Fails! Run-Time error '13' Type Mismatch
        End If
    End If
End With

Allot of people would look at that and say "So what? Its failing with a type mismatch because you have a Byte() and are trying to set a Byte!".

My argument is Fields.Value is a property of Type Variant and given VB6s liberal policies on typecasting I would have figured something like this would work.

Could someone explain why this fails?


Even though it's a variant, it still has the type embedded in it. Please note the image of the VB6 watch window:

Retrieving Binary data from SQL in VB6

Even though the expression is a variant, the type inside the variant is still well defined (string in this case). Thus VB can't just convert a byte array into a byte just because there is only one element in it. The behavior exhibited by your code snippet is perfectly normal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜