如何从ADO记录集字段将图片加载到MS-Access Image控件?

时间:2014-01-29 21:53:58

标签: image ms-access ado recordset

使用:

  1. MS-Access 2013 SP1 x86
  2. MS-SQL Server 2012 SP1 CU8 x64
  3. 通过ODBC DSN连接,SQL Server驱动程序
  4. UpScene Database Workbench Pro v4.4.4 Pro for MS-SQL Server
  5. My Access 2013应用程序使用SQL Server 2012作为ODBC的后端数据库。我正在使用VBA / ADO来读/写数据到数据库。

    到目前为止,我从数据库中检索图像并将其分配给Access窗体上的图像控件时失败了。该映像存储在SQL Server表中(作为VARBINARY(MAX)字段。

    在我将字段分配给Image控件时,它会发出运行时错误:“Type notmatch”。图像存储在数据库中作为位图图像。我之前尝试过Jpeg,但是出现了同样的错误。怎么解决这个问题?

    SQL Server表定义和存储过程定义:

    CREATE TABLE dbo.tbPhoto (
        row_id Int IDENTITY NOT NULL,
        student_id Int NOT NULL,
        picture VarBinary(max),
        date_updated DateTime NOT NULL,
        date_created DateTime NOT NULL, 
        CONSTRAINT PK_tbPhoto PRIMARY KEY CLUSTERED (
          row_id
        )
    )
    

    检索图片的访问程序:

    Private Sub load_studentdetails(AStudentID As Integer)
     On Error GoTo errhnd
    
     objStudent.GetStudentDetails AStudentID, StudentDetailsRS
    
     Set Me.fmStudentReg_DtlA.Form.Recordset = StudentDetailsRS
    ' Me.fmStudentReg_DtlA.Form.Requery
    
     objStudent.GetStudentPicture AStudentID, Me.fmStudentReg_DtlA!imgStudentPic
    
     Exit Sub
    errhnd:
     MsgBox "Error: " & Err.Description
    End Sub
    
    Public Sub GetStudentPicture(AStudentID As Integer, ByRef APicture As Image)
     On Error GoTo errhnd
    
     Dim rs As New ADODB.Recordset
     Set cmd.ActiveConnection = GetDBConnection
    
     cmd.CommandType = adCmdStoredProc
     cmd.CommandText = "dbo.StudentPicture_S"
    
     cmd.Parameters.Refresh
     cmd(1) = AStudentID
    
     rs.CursorLocation = adUseClient
     rs.Open cmd
    
     Set APicture = rs("picture")  '<-----Raises the error: "Type mismatch"
    
     Exit Sub
    errhnd:
     MsgBox "Error: " & Err.Description
    
    End Sub
    

1 个答案:

答案 0 :(得分:0)

由于您已经在使用ADODB.Recordset,我建议您使用ADODB.Stream对象作为中介。我刚刚尝试了以下代码,它对我有用:

Option Compare Database
Option Explicit

Private Sub cmdGetPhoto_Click()
    Dim cdb As DAO.Database
    Dim con As ADODB.Connection, rst As ADODB.Recordset, stm As ADODB.Stream

    Set cdb = CurrentDb
    Set con = New ADODB.Connection
    con.Open Mid(cdb.TableDefs("dbo_Clients").Connect, 6)
    Set rst = New ADODB.Recordset
    rst.Open "SELECT Photo FROM Clients WHERE ClientID=1", con, adOpenStatic, adLockOptimistic
    Set stm = New ADODB.Stream
    stm.Type = adTypeBinary
    stm.Open
    stm.Write rst("Photo").Value  ' write bytes to stream
    stm.Position = 0
    Me.Image0.PictureData = stm.Read  ' load bytes into Image control on form

    stm.Close
    Set stm = Nothing
    rst.Close
    Set rst = Nothing
    con.Close
    Set con = Nothing
    Set cdb = Nothing
End Sub