Junior — Middle
Is it possible to store PDF files directly inside a PostgreSQL database?
sobes.tech AI
Answer from AI
Yes, in PostgreSQL, you can store PDF files directly in the database using the BYTEA data type or Large Object (LOB).
- BYTEA allows storing binary data directly in a table. This is convenient for small files.
- Large Object is a special mechanism for storing large binary data, which can be more efficient when working with large files.
Example of saving a PDF in BYTEA using Java and JDBC:
String sql = "INSERT INTO documents (id, file_data) VALUES (?, ?)";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, documentId);
File pdfFile = new File("file.pdf");
FileInputStream fis = new FileInputStream(pdfFile);
pstmt.setBinaryStream(2, fis, (int) pdfFile.length());
pstmt.executeUpdate();
fis.close();
However, it is worth considering that storing large files in the database can negatively impact performance. It is often recommended to store files in the filesystem or cloud storage, and keep only links to them in the database.