sql >> Database teknologi >  >> RDS >> PostgreSQL

Tom fil efter download

Peter, dette virkede for mig med PostgreSQL 9.3 og Java OpenJDK 7.

Skrivning med 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();
}

Læser stort objekt fra databasen:

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();
    }

Testtabel blev defineret som

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



  1. MySQL swap primære nøgleværdier

  2. uWSGI, Flask, sqlalchemy og postgres:SSL-fejl:dekryptering mislykkedes eller dårlig optagelse mac

  3. CakePHP:Oprettelse af ny HABTM række opdaterer i stedet andre

  4. Tildel samme id til rækker med samme kombination af data