sql >> Base de Datos >  >> RDS >> PostgreSQL

Archivo vacío después de la descarga

Peter, esto me funcionó con PostgreSQL 9.3 y Java OpenJDK 7.

Escribir con LargeObjectAPI:

public static void main(String[] args) throws SQLException, FileNotFoundException, IOException {
    Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test01", "postgres", "postgres");
    conn.setAutoCommit(false);
    File file = new File("/home/user/Pictures/somePicture.jpg");
    FileInputStream fis = new FileInputStream(file);
    LargeObjectManager lom = PGConnection.class.cast(conn).getLargeObjectAPI();
    long oid = lom.createLO(LargeObjectManager.READ | LargeObjectManager.WRITE);
    LargeObject lob = lom.open(oid, LargeObjectManager.WRITE);
    byte[] buffer = new byte[2048];
    int s = 0;
    while ((s = fis.read(buffer, 0, buffer.length)) > 0) {
        lob.write(buffer, 0, s);
    }
    lob.close();
    fis.close();

    PreparedStatement ps = conn.prepareStatement("insert into test(id, name, content) values (nextval('test_id_seq'), ?, ?)");
    ps.setString(1, "foto01");
    ps.setLong(2, oid);
    ps.executeUpdate();
    ps.close();
    conn.commit();
}

Lectura de objetos grandes de la base de datos:

public static void main(String[] args) throws SQLException, FileNotFoundException, IOException {
        Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test01", "postgres", "postgres");
        conn.setAutoCommit(false);

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("select id, name, content from test");

        LargeObjectManager lom = PGConnection.class.cast(conn).getLargeObjectAPI();
        byte[] buffer = new byte[2048];
        int s = 0;
        while(rs.next()) {
            File file = new File("/tmp", rs.getLong("id") + "_" + rs.getString("name"));
            FileOutputStream fos = new FileOutputStream(file);
            LargeObject lob = lom.open(rs.getLong("content"), LargeObjectManager.READ);
            while((s = lob.read(buffer, 0, buffer.length)) > 0) {
                fos.write(buffer, 0, buffer.length);
            }
            lob.close();
            fos.close();
        }

        conn.close();
    }

La tabla de prueba se definió como

create table test (id serial, name varchar(256), content oid);