簡體   English   中英

使用 Excel Z6E3EC948E6A9F93008B 將文件(如 PDF、圖像、Word...)上傳到 SQL 服務器中的表

[英]Upload files (like PDF, image, Word…) to a table in SQL Server using Excel VBA

I have an Excel file that a few users are using it as a front-end And I want to be able to upload via VBA a general files (like PDF, image, word document...) to SQL Server.

在搜索了許多網站后,我整理了一些代碼,但我不知道在 VBA SQL 變量(INSERT INTO 查詢)中寫什么,以便上傳一些通用文件(如 ZBCD1B68617759B1DFCFF0403A6B 示例)

VBA 代碼:

Sub SaveAsBinary()

    Dim adoStream As Object
    Dim adoCmd As Object
    Dim strFilePath As String
    Dim adoCon As Object
  
    Dim SQL As String
    Dim FileNameStr as String
  
    
    Set adoCon = CreateObject("ADODB.Connection")
    Set adoStream = CreateObject("ADODB.Stream")
    Set adoCmd = CreateObject("ADODB.Command")
    
    '--Open Connection to SQL server
    adoCon.CursorLocation = 3 'adUseClient
    
    adoCon.Open = "Driver={SQL Server Native Client 11.0};" _
                        & "MyServerName;" _
                        & "Database=MyDatabaseName;" _
                        & "Uid=MyUserName;" _
                        & "Pwd={MyPassword};" _
                        & "Connection Timeout=30;"
    
    
    '----
    
    strFilePath = Range("a1").Value 'keep File path to upload (simple local computer path)
    FileNameStr = Dir(strFilePath )
    
    SQL = "INSERT INTO Tbl_Test VALUES (FileNameStr, ??)" '‹‹---What value should be here for loading a pdf file (for example)

    
    adoStream.Type = 1 'adTypeBinary
    adoStream.Open
    adoStream.LoadFromFile strFilePath 'It fails if file is open
        
    With adoCmd
        .CommandText = SQL ' Query
        .CommandType = 1 ' adCmdText
        
        '---adding parameters
        .Parameters.Append .CreateParameter("@FileName", 20, 1, 0, 1)
        .Parameters.Append .CreateParameter("@MyFile", 204, 1, adoStream.Size, adoStream.Read)
        '---
    End With
    
    adoCmd.ActiveConnection = adoCon
    adoCmd.Execute
        
    adoCon.Close
    
End Sub

原始代碼取自: https://usefulgyaan.wordpress.com/2014/09/30/store-and-fetch-files-sql-server-tables/

Sql 服務器中的表:

CREATE TABLE [dbo].[Tbl_Test](
    [FileName] [nvarchar](200) NOT NULL,
    [MyFile] [varbinary](max) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

一列用於文件名,一列用於文件本身。

注意:SQL 服務器位於沒有共享文件夾/BLOB/FTP 的遠程服務器上。

解決方案是將線路保持為

SQL = "INSERT INTO Tbl_Test VALUES (?, ?)"

並將參數填寫到 SQL 中

.Parameters.Append .CreateParameter("@FileName", 20, 1, 0, 1)
.Parameters.Append .CreateParameter("@MyFile", 204, 1, adoStream.Size, adoStream.Read)

使用CreateParameter 方法和適合數據庫字段的數據類型。

我會這樣做:

SQL = "INSERT INTO Tbl_Test([FileName],[MyFile]) VALUES ('" & FileNameStr & "', CAST(" & adoStream.Read & ") as varbinary(max))"

備注:未在 VBA 中測試 - 我是 AutoIt 編碼器,而不是 VBA 編碼器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM