Pedro - 2023-10-01

Hello guys, I'll explain the situation to you.
I have a table in an access database that contains a field of type attachments, and I cannot update that field, specifically I am trying to add a new text file to an already saved record.
This is the code I am using:

public void AddFile(int id, File file) {
try {

        Attachment newFile = ConvertToAttachment(file);

        try {
            Conexion conect1 = new Conexion(dbName);
            Connection con1 = conect1.getConnection();

            String sql = "UPDATE Alineador SET [Campo2] = ? WHERE ID = " + id;
            PreparedStatement pst = con1.prepareStatement(sql);


           Attachment[] oldFiles = GetCurrentFiles(id);

           Attachment[] updatedFiles = new Attachment[oldFiles.length +1];

           for (int i =0; i< oldFiles.length; i++)
           {
                updatedFiles[i] = oldFiles[i];
            }
            updatedFiles[updatedFiles.length -1] = newFile;

            pst.setBytes(1, ConvertToBytes(updatedFiles));

            pst.executeUpdate();

        } catch (SQLException e) {
            System.out.println("SQL EXCEPTION in AddFile" + e);
            e.printStackTrace();

        }
    } catch (IOException ex) {
        Logger.getLogger(Tabla1Frame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

    private Attachment ConvertToAttachment(File file) throws IOException
{
    String name = file.getName();
    String type = "txt";
    byte[] data = readFile(file);

    Attachment att = new Attachment(null, name, type, data, null, null);

    return att;       
}

private static byte[] readFile(File file) throws IOException {
    FileInputStream inputStream = new FileInputStream(file);
    byte[] fileBytes = new byte[inputStream.available()];
    inputStream.read(fileBytes);
    inputStream.close();
    return fileBytes;
}

    private Attachment[] GetCurrentFiles(int id)
{
    Attachment[] atts = null;
    try {
        Conexion conect1 = new Conexion("ALINEADORES.accdb");
        Connection con1 = conect1.getConnection();

        String sql = "SELECT Campo2 FROM Alineador WHERE Id = '" + id + "'";
        Statement st = con1.createStatement();
        ResultSet rs = st.executeQuery(sql);

        if (rs.next()) {
            atts = (Attachment[]) rs.getObject(1);
            return atts;
        }
    } catch (SQLException e) {

    }
    return atts;
}

    private static byte [] ConvertToBytes(Attachment[] attachments)
 {
    int totalLength = 0;
    for (Attachment attachment : attachments) {
        totalLength += attachment.getData().length;
    }

    byte[] bytes = new byte[totalLength];
    int currentIndex = 0;

    for (Attachment attachment : attachments) {
        byte[] attachmentData = attachment.getData();
        System.arraycopy(attachmentData, 0, bytes, currentIndex, attachmentData.length);
        currentIndex += attachmentData.length;
    }

    return bytes;
 }