ADOを使用してSQLServerのVarBinary列にバイナリデータとしてファイルをアップロードおよびダウンロードすることをテストするための小さなVBAプロシージャを作成しました。アップロードプロセスは機能しているように見えますが、ダウンロードプロセスを機能させることができません。
VarBinaryの出力パラメータが正しく設定されていないと思いますが、正しく設定する方法に関するドキュメントが見つかりません。
実行時エラー3708「パラメータオブジェクトが正しく定義されていません。一貫性のない、または不完全な情報が提供されました。」が表示されます。ラインで.Parameters.Append .CreateParameter("@myblob", adVarBinary, adParamOutput)
更新:SELECT ? = myblob FROM bin_table WHERE ID = ?;バイナリ配列ではなく、バイナリ文字列を返しているようです。これが問題の原因だと思いますが、それを修正する方法がまだわかりません。
更新.Value:行末にaddingを追加することで、コンパイルエラー「型の不一致:配列またはユーザー定義型が必要です」を修正しましたWriteFile "C:\some_new_file.pdf", .Parameters("@myblob")。
どんな助けでも大歓迎です。ありがとう!
Private Sub TestReadWriteBlob()
Dim objConnection As New ADODB.Connection
Dim objCommand As New ADODB.Command
Dim objRecordset As New ADODB.Recordset
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:\some_file.pdf"))
.Parameters.Append .CreateParameter("@NewID", adInteger, adParamOutput)
.Execute
intNewID = .Parameters("@NewID")
End With
Debug.Print intNewID
Set objCommand = Nothing
With objCommand
.ActiveConnection = objConnection
.CommandText = "SELECT ? = myblob FROM bin_table WHERE ID = ?;"
.CommandType = adCmdText
.Parameters.Append .CreateParameter("@myblob", adVarBinary, adParamOutput)
.Parameters.Append .CreateParameter("@NewID", adInteger, adParamInput, , intNewID)
.Execute
WriteFile "C:\some_new_file.pdf", .Parameters("@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