我已经用Google搜索了如何在数据库中存储图像的基本问题,并找到了许多示例。但是,我所看到的所有答案(例如this)似乎都使用SQLCommand作为解决方案,无论他们是使用旧的“图像”类型,文本还是建议VARCHAR(MAX)。我正在使用SQL 2008和SQL 2012
我无法将此功能合并到我的应用中,因为我有一个遗留的dll可以做其他工作,然后存储我的图像。我想将其包装成SQL事务。挑战是DLL本质上是一个黑盒子,因为我无法更改源代码。 Dll公开了一个可选SQL语句的参数,它可以作为事务的一部分运行。
DLL的结构是这样的:
Public Class MyClass
Public Property ExtraSQL as string
Public Function DoWork
Dim sMainSQL as String
'Start A transaction
Execute(sMainSQL)
If ExtraSQL <> "" Then
Execute(ExtraSQL)
End If
If OK Then Commit Transaction
End Function
End Class
我的目标是将SQL字符串提供给属性ExtraSQL,但我不知道如何执行此操作,因为所有示例都指示了SqlCommand.Parameters(@Image).Value = byteArray()。我从Web服务获取图像数据。在其生命周期中,它被格式化为Image,base64编码字符串,内存流和字节数组,因此在类型之间进行转换不是问题。我只是不清楚最干净的语法。最好只取我原来的base64字符串并执行以下操作:
INSERT INTO tblImage (ImageData) Values ('Base64 blah blah')
然后每当我读回图像时都这样做:
Public Function Base64ToImage(ByVal base64String As String) As System.Drawing.Image
Dim img As System.Drawing.Image = Nothing
Try
'Convert Base64 string to byte array
Dim btImage As Byte() = Convert.FromBase64String(base64String)
Dim ms As New IO.MemoryStream(btImage, 0, btImage.Length)
ms.Write(btImage, 0, btImage.Length)
img = System.Drawing.Image.FromStream(ms, True)
Catch ex As Exception
End Try
Return img
End Function
我将不胜感激任何支持链接,示例和建议。提前谢谢。
答案 0 :(得分:1)
好吧,考虑到你显然无法发送参数化的SQL,是的,这是最好的方法。我肯定不喜欢它,因为它对SQL注入很开放。我会考虑反编译您正在使用的程序集,并在将来将其作为我自己的源代码。