PostgreSQL
 SQL >> Database >  >> RDS >> PostgreSQL

Memorizzare e recuperare immagini in PostgreSQL con Java

Il capitolo 7 della documentazione JDBC di PostgreSQL copre la memorizzazione di dati binari e usa un'immagine (*.gif) come esempio: vale la pena leggerlo.

Inserire un'immagine nel database (da quel link):

File file = new File("myimage.gif"); FileInputStream fis = new FileInputStream(file); PreparedStatement ps = conn.prepareStatement("INSERT INTO images VALUES (?, ?)"); ps.setString(1, file.getName()); ps.setBinaryStream(2, fis, (int)file.length()); ps.executeUpdate(); ps.close(); fis.close(); 

Leggere un'immagine (sempre da quel link):

// Get the Large Object Manager to perform operations with LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI(); PreparedStatement ps = conn.prepareStatement("SELECT imgoid FROM imageslo WHERE imgname = ?"); ps.setString(1, "myimage.gif"); ResultSet rs = ps.executeQuery(); while (rs.next()) { // Open the large object for reading int oid = rs.getInt(1); LargeObject obj = lobj.open(oid, LargeObjectManager.READ); // Read the data byte buf[] = new byte[obj.size()]; obj.read(buf, 0, obj.size()); // Do something with the data read here // Close the object obj.close(); } rs.close(); ps.close();