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 {
AttachmentnewFile=ConvertToAttachment(file);try{Conexionconect1=newConexion(dbName);Connectioncon1=conect1.getConnection();Stringsql="UPDATE Alineador SET [Campo2] = ? WHERE ID = "+id;PreparedStatementpst=con1.prepareStatement(sql);Attachment[]oldFiles=GetCurrentFiles(id);Attachment[]updatedFiles=newAttachment[oldFiles.length +1];for(inti=0;i<oldFiles.length;i++){updatedFiles[i]=oldFiles[i];}updatedFiles[updatedFiles.length -1]=newFile;pst.setBytes(1,ConvertToBytes(updatedFiles));pst.executeUpdate();}catch(SQLExceptione){System.out.println("SQL EXCEPTION in AddFile"+e);e.printStackTrace();}}catch(IOExceptionex){Logger.getLogger(Tabla1Frame.class.getName()).log(Level.SEVERE,null,ex);}}privateAttachmentConvertToAttachment(Filefile)throwsIOException{Stringname=file.getName();Stringtype="txt";byte[]data=readFile(file);Attachmentatt=newAttachment(null,name,type,data,null,null);returnatt;}privatestaticbyte[]readFile(Filefile)throwsIOException{FileInputStreaminputStream=newFileInputStream(file);byte[]fileBytes=newbyte[inputStream.available()];inputStream.read(fileBytes);inputStream.close();returnfileBytes;}privateAttachment[]GetCurrentFiles(intid){Attachment[]atts=null;try{Conexionconect1=newConexion("ALINEADORES.accdb");Connectioncon1=conect1.getConnection();Stringsql="SELECT Campo2 FROM Alineador WHERE Id = '"+id+"'";Statementst=con1.createStatement();ResultSetrs=st.executeQuery(sql);if(rs.next()){atts=(Attachment[])rs.getObject(1);returnatts;}}catch(SQLExceptione){}returnatts;}privatestaticbyte[]ConvertToBytes(Attachment[]attachments){inttotalLength=0;for(Attachmentattachment:attachments){totalLength+=attachment.getData().length;}byte[]bytes=newbyte[totalLength];intcurrentIndex=0;for(Attachmentattachment:attachments){byte[]attachmentData=attachment.getData();System.arraycopy(attachmentData,0,bytes,currentIndex,attachmentData.length);currentIndex+=attachmentData.length;}returnbytes;}
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
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 {