Can I return a byte array from a SQL Server VarBinary column using a parameterized query?

风流意气都作罢 提交于 2019-12-01 08:34:39

I could not find any way to return the byte array from the VarBinary column in SQL Server using a parameter. I did, however, figure out that doing it from the recordset works. The attached code does the job.

I am still looking for a way to use the parameter to return the byte array and will hold out on accepting an answer for a few days in case someone has a solution.

Private Sub TestReadWriteBlob()

    Dim objConnection As New ADODB.Connection
    Dim objCommand As New ADODB.Command
    Dim intNewID As Integer

    With objConnection
        .CursorLocation = adUseClient
        .ConnectionString = "PROVIDER=SQLOLEDB;Server=<server>;Database=<database>;UID=<uid>;PWD=<pwd>;trusted_connection=false;"
        .Open
    End With

    With objCommand
        .ActiveConnection = objConnection
        .CommandText = "INSERT INTO bin_table ( myblob ) VALUES ( ? ); SELECT ? = id FROM bin_table WHERE ID = @@IDENTITY;"
        .CommandType = adCmdText
        .Parameters.Append .CreateParameter("@myblob", adVarBinary, adParamInput, -1, ReadFile("C:\Users\Thomas\Desktop\some_file.pdf"))
        .Parameters.Append .CreateParameter("@NewID", adInteger, adParamOutput)
        .Execute
        intNewID = .Parameters("@NewID")
    End With

    Set objCommand = Nothing
    With objCommand
        .ActiveConnection = objConnection
        .CommandText = "SELECT myblob FROM bin_table WHERE ID = ?;"
        .CommandType = adCmdText
        .Parameters.Append .CreateParameter("@NewID", adInteger, adParamInput, , intNewID)
        WriteFile "C:\Users\Thomas\Desktop\blob\some_file.pdf", .Execute.Fields("myblob").Value
    End With

End Sub

Public Function ReadFile(ByVal strPath As String) As Byte()

    Dim intFile As Integer

    intFile = FreeFile
    Open strPath For Binary Access Read As intFile
    ReDim ReadFile(LOF(intFile) - 1)
    Get intFile, , ReadFile
    Close intFile

End Function

Public Sub WriteFile(ByVal strPath As String, bytBlob() As Byte, Optional ByVal Overwrite As Boolean = True)

    Dim intFile As Integer

    intFile = FreeFile
    If Overwrite And Dir(strPath) <> "" Then
        Kill strPath
    End If
    Open strPath For Binary Access Write As intFile
    Put intFile, , bytBlob
    Close intFile

End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!