使用VBA将文件插入SQL Server的问题

时间:2018-10-10 15:02:57

标签: sql-server vba

我正在尝试将以下代码合并到现有代码中。

这是我有效的测试代码:

Sub test()
Dim con As ADODB.Connection
Dim rs As ADODB.recordSet
Set con = New ADODB.Connection
Set rs = New ADODB.recordSet

con.Open "Provider=SQLOLEDB;Password=;User ID=;Initial 
Catalog='" & Worksheets("Settings").Range("C2").Value & _
        "';Data Source='" & Worksheets("Settings").Range("A2").Value & "';"

'Open database connection
rs.ActiveConnection = con

rs.Open "select * from QuoteData", con, adOpenKeyset, 
adLockOptimistic

Set mstream = New ADODB.Stream
mstream.Type = adTypeBinary
mstream.Open
mstream.LoadFromFile "c:\temp\pictures\pic1.jpg"
rs.Fields("PII_Image1").Value = mstream.Read
rs.Update
End Sub

这是我在现有代码中使用的代码。 UpdateQuery是较大字符串的一部分。我想将其与我现有的更新查询集成。

Set mstream = New ADODB.Stream
mstream.Type = adTypeBinary
mstream.Open
mstream.LoadFromFile "c:\temp\pictures\pic1.jpg"
updateQuery = updateQuery & "PII_Image1=convert(varbinary(MAX),'mstream.Read'),"
mstream.Close

此代码可以运行,但是它只会在数据库中插入看起来像“ 0x6D73747265616D2E52656164”的东西,这是不正确的。我试图找出原因。如果我拿走转换件,它说它不能将varchar转换为varbinary(MAX)

1 个答案:

答案 0 :(得分:1)

使用updateQuery = updateQuery & "PII_Image1 = 0x" & BinaryToHex(mstream.Read) & "),"

此外,将以下功能添加到您的模块中:

'Simple binary-to-hex Function
'2003 Antonin Foller, Motobit Software
'BinaryToHex is byte-to-byte VBS function and it is suitable only for small amount of binary data - up to 100kB.
'If you want to work with bigger size, please see HexString property of Motobit's ScriptUtil.ByteArray object.

Private Function BinaryToHex(Binary)
  Dim c1, Out, OneByte

  'For each source byte
  For c1 = 1 To LenB(Binary)
    'Get the byte As hex
    OneByte = Hex(AscB(MidB(Binary, c1, 1)))

    'append zero For bytes < 0x10
    If Len(OneByte) = 1 Then OneByte = "0" & OneByte

    'join the byte To OutPut stream
    Out = Out & OneByte
  Next

  'Set OutPut value
  BinaryToHex = Out
End Function