Storing an image into an Attachment field in an Access database

主宰稳场 提交于 2019-11-26 17:58:30

As you have discovered, you cannot use a SQL statement to insert files into an Attachment field in an Access database. You have to use the LoadFromFile() method of an ACE DAO Field2 object. The following C# code works for me. It is adapted from the Office Blog entry here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Access.Dao;

namespace daoConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // This code requires the following COM reference in your project:
            //
            // Microsoft Office 14.0 Access Database Engine Object Library
            //
            var dbe = new DBEngine();
            Database db = dbe.OpenDatabase(@"C:\__tmp\testData.accdb");
            try
            {
                Recordset rstMain = db.OpenRecordset(
                        "SELECT refId, img FROM Logo WHERE refId = 1", 
                        RecordsetTypeEnum.dbOpenDynaset);
                if (rstMain.EOF)
                {
                    // record does not already exist in [Logo] table, so add it
                    rstMain.AddNew();
                    rstMain.Fields["refId"].Value = 1;
                }
                else
                {
                    rstMain.Edit();
                }
                // retrieve Recordset2 object for (potentially multi-valued) [img] field
                //     of the current record in rstMain
                Recordset2 rstAttach = rstMain.Fields["img"].Value;
                rstAttach.AddNew();
                Field2 fldAttach = 
                        (Field2)rstAttach.Fields["FileData"];
                fldAttach.LoadFromFile(@"C:\__tmp\testImage.jpg");
                rstAttach.Update();
                rstAttach.Close();
                rstMain.Update();
                rstMain.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

I did the same thing based off of the above code and the blog entry from here.

Here is my vb.net code which allows me to do an OpenFileDialog and multiple selections and the function will handle storing multiple files just fine. Though I did have to add a reference to my project for Microsoft Office 15.0 Access database engine Object Library to get it to work properly. I think you can go down to 12.0 or 14.0 as well.

Private Sub AddAttachment(ByVal Files() As String)
    Const Caller = "AddAttachment"
    Dim dbe = New Microsoft.Office.Interop.Access.Dao.DBEngine()
    Dim db As Microsoft.Office.Interop.Access.Dao.Database
    db = dbe.OpenDatabase(dbPath)
    Try
        Dim rstMain As Microsoft.Office.Interop.Access.Dao.Recordset
        rstMain = db.OpenRecordset("SELECT ID, fieldName FROM tableName WHERE ID = " + (dt.Rows(currentRow).Item("ID").ToString), Microsoft.Office.Interop.Access.Dao.RecordsetTypeEnum.dbOpenDynaset)
        If (rstMain.EOF) Then
            rstMain.AddNew()
            rstMain.Fields("ID").Value = 1
        Else
            For Each value As String In Files
                rstMain.Edit()
                Dim rstAttach As Microsoft.Office.Interop.Access.Dao.Recordset2
                rstAttach = rstMain.Fields("ATTACHMENTS").Value
                rstAttach.AddNew()
                Dim fldAttach As Microsoft.Office.Interop.Access.Dao.Field2
                fldAttach = rstAttach.Fields("FileData")
                fldAttach.LoadFromFile(value)
                rstAttach.Update()
                rstAttach.Close()
            Next
            rstMain.Update()
            rstMain.Close()
        End If

    Catch ex As Exception
        If Err.Number <> 3820 Then
            MsgBox(ex.Message)
        Else
            MsgBox("File of same name already attached", MsgBoxStyle.Critical, "Cannot attach file" & Caller)
            MessageBox.Show(ex.Message)
        End If

    End Try
End Sub

I'm now working on the functions to RemoveAttachments and save files from the attachements field. I'll post those here later.

Another thing to add to this. If your database is encrypted then you will need to add to the OpenDatabase command.

This is the code I used in C# but the VB.NET code will be very similiar. db = dbe.OpenDatabase(dbPath, false, false,"MS Access;PWD=password");

It took me ages to try and track this down on my own and I will try break down the various parts of the method. The MSDN Article for it can be found here.

1st Argument: dbPath, that's the same as the usage in the original post. The location and filename of the database you want to open.

2nd Argument: false. This is a true/false argument that if true opens the database in Exclusive-Mode. So that only this single program can use it. Most of the time this should be false. Only use exclusive mode if you have to.

3rd Argument: false. This is another true/false argument. This time if it's true then it opens the database in Read-only mode.This means you can only use recordsets to read information and you cannot use the Edit, Add or Delete methods. This can be true or false depending on your needs.

4th Argument: This sets specific properties in how to open the database. In this case. It says to set the Microsoft Access property 'PWD' to 'password'. In this property setting will tell method to open up an encrypted database using the password 'password'. Of course you will need to change "password" to whatever the database's actual password is to open but I'd been hunting this down for a while.

I hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!