使用:
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
答案 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