在 VB6 中从 SQL 检索二进制数据
如果您在 SQL 中有一个二进制类型的列,并使用 VB6 中的 ADODB 返回它,即使该列仅包含 1 个字节的数据,也必须将其存储为字节数组。
例如:
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
很多人会看着它并说“那又怎样?它因类型不匹配而失败,因为你有一个 Byte() 并试图设置一个 Byte!”。
我的论点是 Fields.Value 是 Type Variant 的一个属性,并且考虑到 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尽管它是一个变体,但它仍然嵌入了类型。请注意 VB6 监视窗口的图像:
即使表达式是变体,内部的类型变体仍然定义良好(在本例中为字符串)。因此,VB 不能仅仅因为其中只有一个元素就将字节数组转换为字节。您的代码片段所表现出的行为是完全正常的。
Even though it's a variant, it still has the type embedded in it. Please note the image of the VB6 watch window:
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.